父指令属性更改时,子指令未更新
这是以下两个问题的后续内容:
This is follow up to these 2 questions:
- Pass argument between parent and child directives
- Parent directive controller undefined when passing to child directive
我正在这部分工作;但是,当父指令的ng-disabled值更改时,子指令的值将不会更新.
I have this part working; however, when the value for ng-disabled for parent directive changes, the child directive values don't get updated.
请参见 plunkr示例.
HTML:
<div ng-app="myApp">
<div ng-controller="MyController">
{{menuStatus}}
<tmp-menu ng-disabled="menuStatus">
<tmp-menu-link></tmp-menu-link>
<tmp-menu-link></tmp-menu-link>
</tmp-menu>
<button ng-click="updateStatus()">Update</button>
</div>
</div>
JavaScript(AngularJS):
JavaScript(AngularJS):
angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.controller('MyController', function($scope){
$scope.menuStatus = false;
$scope.updateStatus = function(){
$scope.menuStatus = $scope.menuStatus?false:true;
}
})
.directive('tmpMenu', function() {
return {
restrict: 'AE',
replace:true,
transclude:true,
scope:{
disabled: '=?ngDisabled'
},
controller: 'MyDirectiveController',
template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
link: function(scope, element, attrs) {
}
};
})
.directive('tmpMenuLink', function() {
return {
restrict: 'AE',
replace:true,
transclude:true,
scope:{
},
require:'^^tmpMenu',
template: '<div>childDirective disabled: {{ disabled }}</div>',
link: function(scope, element, attrs, MyDirectiveCtrl) {
console.log(MyDirectiveCtrl);
scope.disabled = MyDirectiveCtrl.isDisabled();
}
};
})
function MyDirectiveController($scope) {
this.isDisabled = function() {
return $scope.disabled;
};
}
如何在不添加角度监视程序的情况下检测父指令中的更改并将其传递给子指令.
How can I detect change in parent directive and pass it to child directive without adding angular watcher.
解决方案1
我在这里设置了有效的plnkr: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p =预览
i've set up a working plnkr here: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview
此行为的原因是tmpMenuLink
保留了MyDirectiveCtrl.isDisabled()
返回的值的副本.没有设置观察者,因此解决此问题的唯一方法是手动观察任何更改,然后更新该字段.
the reason of this behaviour is that tmpMenuLink
kept a copy of the value returned from MyDirectiveCtrl.isDisabled()
. no watcher is set up , so the only way to resolve this is to manually watch for any changes and then update the field.
scope.$watch(function(){
return MyDirectiveCtrl.isDisabled();
}, function(){
scope.disabled = MyDirectiveCtrl.isDisabled();
})
解决方案2
没有观察者的替代方法是传递对象的引用,而不是原始类型,例如:
An alternative without watchers is to pass the reference of an object instead of a primitive type, something like:
$scope.menuStatus = {status: false};
此处的新plnkr: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview
new plnkr here: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview