【发布时间】: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>
【问题讨论】:
标签: javascript angularjs angularjs-directive