簡體   English   中英

在父指令的控制器上使用角度監視

[英]Angular watch on parent directive's controller with require

我有一個帶有控制器的父子指令,這兩個子指令在子指令中都是必需的。 我想監視子指令的鏈接功能內父指令控制器上的屬性更改。 但是,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>

小提琴

在您正在觀察的范圍內,父控制器是“ parentCtrl”而不是“ parentController”,因此您實際上並沒有在觀察要成為的屬性。 以下應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM