首页 文章

带有require的父指令控制器上的Angular监视

提问于
浏览
0

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

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

Parent directive

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);
        }
    } });

Child directive

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';
            });
        }
    }
});

View

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

Fiddle .

1 回答

  • 3

    在你正在观看的范围内,父控制器是'parentCtrl'而不是'parentController',所以你实际上并没有看到你想要的属性 . 以下应该有效:

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

相关问题