AngularJS - 如何通过嵌套(自定义)指令将数据从子级传递到父级

AngularJS - How to pass data through nested (custom) directives from child to parent

我正在寻找通过嵌套指令发送作用域的最佳方式。

我发现您可以 $scope.$parent.value,但我知道这不是最佳做法,应该避免。

所以我的问题是,如果我有 4 个如下所示的嵌套指令,每个指令都有自己的控制器,其中一些数据正在被修改,那么从指令 4 访问值的最佳方法是什么(假设 $scope.valueFromDirective4)在指令 1 中?

<directive1>
    <directive2>
        <directive3>
            <directive4>
            </directive4>
        </directive3>
    </directive2>
</directive1>

嵌套指令始终可以通过 require 访问其父级的控制器。假设您想从 directive1 的任何嵌套指令的作用域中更改 value。实现这一点的一种可能方法是在 directive1 的控制器 setValue(value) 中声明一个 setter。然后在任何嵌套指令中,您需要要求 directive1 的控制器,这样您就可以访问 setter setValue(value) 和控制器提供的其他方法。

angular
  .module('yourModule')
  .directive('directive1', function() {
    return {
      controller:['$scope', funciton($scope) {
        return {
          setValue: setValue
        };

        funciton setValue(value) {
          $scope.value = value;
        }
      }]
      // The rest of the directive1's configuration
    };
  })
  .directive('directive4', function() {
    return {
      require: '^^directive1',
      link: (scope, elem, attrs, directive1Ctrl) {
        // Here you can call directive1Ctrl.setValue() directly
      }
      // The rest of the directive4's configuration
    };
  })

另一种方法是在 value 被子指令更改时从子指令的控制器发送 $emit 事件。在这种情况下,父指令的控制器应该订阅该事件并处理与其一起传递的数据。

对于 "presentational" / "dumb" 组件(directive3directive4),我认为它们都应该接受一个回调函数,它们可以用新数据调用当他们改变时:

scope: {
    // Invoke this with new data
    onChange: '&',
    // Optional if you want to bind the data yourself and then call `onChange`
    data: '='
}

只需将回调从 directive2 传递到 directive4。这样 directive3directive4 就与您的应用程序分离并且可以重复使用。

如果它们是类似表单的指令(类似于 input 等),另一种选择是让它们要求 ngModel 并让它们使用 ngModelController 来更新父级和查看。 (查找 $render$setViewValue 了解更多信息)。这样您就可以像这样使用它们:

<directive4 ng-model="someObj.someProp" ng-change="someFunc()"></directive4>

当您这样做时,模型更新后会自动调用 ng-change 函数。

对于 "container" / "smart" 指令(directive1directive2),您还可以让 directive2 接受传入的回调来自 directive1。但是由于 directive1directive2 都可以知道您的应用程序,您可以编写一个服务,在 directive1directive2.

之间注入和共享