我有一个父指令和子指令,每个指令都有一个 Controller ,子指令中都需要这两个指令。我想在子指令的链接函数中监视父指令 Controller 上的属性的更改。但是,监视函数会在初始化时触发,但随后当通过父指令作用域中的按钮或父指令的链接函数更改属性时不会触发。
请有人解释一下这是为什么以及我应该如何解决它?
家长指令
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 .
最佳答案
在您正在观看的范围内,父 Controller 是“parentCtrl”而不是“parentController”,因此您实际上并没有在观看您想要的属性。以下内容应该有效:
scope.$watch('parentCtrl.someProperty', function () {
controller.someProperty = parentController.someProperty
? 'Hello world!' : 'Goodbye cruel world';
});
关于javascript - 带有 require 的父指令 Controller 上的 Angular 监视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916598/