Angular监视父指令的控制器和require

时间:2015-10-02 22:12:11

标签: javascript angularjs angularjs-directive

我有一个带有控制器的父和子指令,这两个指令在子指令中都是必需的。我想在子指令的link函数中监视父指令控制器上属性的更改。但是,watch函数在初始化时触发,但后来在父指令范围内的按钮或父指令的链接函数更改属性时触发。

请有人解释为什么会这样,我该如何解决?

家长指示

myApp.directive('parentDirective', function ($timeout) {
    return {
        restrict: 'E',
        scope: true,
        controllerAs: 'parentCtrl',
        controller: function () {
            var vm = this;
            vm.someProperty = true;
            vm.toggle = function () {
                vm.someProperty = !vm.someProperty;
            }
        },
        link: function (scope, element, attrs, controller) {
            $timeout(function () {
                controller.toggle();
            }, 1000);
        }
    } });

儿童指令

myApp.directive('childDirective', function () {
    return {
        restrict: 'E',
        scope: true,
        require: ['childDirective', '^parentDirective'],
        controllerAs: 'childCtrl',
        controller: function () {
            var vm = this;
            vm.someProperty = '';
        },
        link: function (scope, element, attrs, controllers) {

            var controller = controllers[0];
            var parentController = controllers[1];

            scope.$watch('parentController.someProperty', function () {
                controller.someProperty = parentController.someProperty 
                    ? 'Hello world!' : 'Goodbye cruel world';
            });
        }
    }
});

查看

<parent-directive>
    <button ng-click="parentCtrl.toggle()">Toggle message</button>
    <child-directive>
        <p>{{childCtrl.someProperty}}</p>
    </child-directive>
</parent-directive>

Fiddle

1 个答案:

答案 0 :(得分:3)

在您正在观看的范围内,父控制器是“父母控制”&#39;而不是&#39; parentController&#39;,所以你实际上并没有真正关注你想成为的房产。以下应该有效:

scope.$watch('parentCtrl.someProperty', function () {
  controller.someProperty = parentController.someProperty 
    ? 'Hello world!' : 'Goodbye cruel world';
});