作为 angularjs 指令的函数触发属性

Trigger an attribute as function of angularjs directive

我将这个 html 模板放入 fileA.directive.html:

<md-button ng-click="resetForm()" class="btn btn-primary">Reset form</md-button>
<user-form reset-user-fn=""></user-form>

并进入我的 fileA.directive.js:

app.directive("shopAppFormCustomer", function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "fileA.directive.html",
      scope: {},
      controller: [
        "$scope",
        function($scope) {
          $scope.resetForm = function () {
             // want to call reset-user-fn here
          }
        }
      ]
    };
  })

进入我的 fileB.directive.js,我有 userForm 指令

app.directive("userForm", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "fileB.directive.html",
    scope: {resetUserFn: "=" },
    controller: [
       "$scope",
        function ($scope) {
          $scope.resetUserFn = function () {
             // reset goes here
          }
        }
    ]
  }

这是我的问题:

如何将属性 resetUserFn 触发到我的 fileB.directive.js 到我的 fileA.directive.js?

请提供任何来源或文档。

注意:如果可能的话,我不会使用自定义事件。

您应该创建一个公共 service 以便您可以在任何您想要的地方使用服务中的所有内容。在这种情况下,可以在 fileA.directive.js 和 fileB.directive.js 中使用的函数。

所以你想从父指令触发子指令的一些方法。不幸的是,AngularJS 没有对此类问题的原生支持。这里有一些解决方法供您考虑

  1. 使用内置的事件调度器,here is很好的解释。
  2. 基于组件的 $onChanges 方法,described here
  3. 每个 angular 服务都是单例,因此您可以创建一个 service,用于父子通信。

每种方法都很丑陋!

  1. 事件调度程序 - 太多的事件可能会显着降低应用程序的速度。您最终可能会遇到数百个很难维护的事件。
  2. $onChanges - 代码看起来很难看,难以维护。
  3. 每个案例都需要一个新服务,很难维护。

我想它不受本地支持的原因有一些。如果在 shopAppFormCustomer 父指令下有两个或更多 <user-form reset-user-fn=""></user-form> 指令怎么办?你想调用一个特定的 userForm 指令的 resetUserFn,如何区分一个 userForm 和另一个 userForm

这在 Angualar 2 及更高版本中得到了某种支持,但解决方案也不完美。所以你只需要从上面选择哪个解决方案对你来说不那么痛苦并处理它。

<md-button ng-click="resetForm()" class="btn btn-primary">
  Reset form
</md-button>
̶<̶u̶s̶e̶r̶-̶f̶o̶r̶m̶ ̶r̶e̶s̶e̶t̶-̶u̶s̶e̶r̶-̶f̶n̶=̶"̶"̶>̶
<user-form reset-user-fn="resetForm">
</user-form>

<user-form> 指令将父作用域 属性 resetForm 分配给函数的引用。 ng-click 指令调用该函数。

为避免内存泄漏,请确保在销毁隔离作用域时null 属性。

app.directive("userForm", function() {
  return {
    restrict: "E",
    templateUrl: "fileB.directive.html",
    scope: {resetUserFn: "=" },
    controller: function ($scope) {
        $scope.resetUserFn = function () {
            // reset goes here
        };
        $scope.$on("$destroy", function() {
            $scope.resetUserFn = null;
        });
    } 
  }        
}