【问题标题】:Angular watch on parent directive's controller with require使用 require 对父指令的控制器进行角度监视
【发布时间】:2015-10-02 22:12:10
【问题描述】:

我有一个父子指令和一个控制器,它们都是子指令所必需的。我想在子指令的链接函数中观察父指令控制器上属性的变化。但是,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.

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    在您正在观看的范围内,父控制器是“parentCtrl”而不是“parentController”,因此您实际上并没有观看您想要成为的属性。以下应该有效:

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

    【讨论】:

    • 谢谢伙计。就是看不出来!
    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2015-07-20
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多