javascript - Angular watch on parent directive's controller with require -
i have parent , child directive controller each, both of required in child directive. want watch changes property on parent directive controller within link function of child directive. however, watch function fired on initialisation not subsequently when property changed button in parent directive's scope, or link function of parent directive.
please explain why , how should resolve it?
parent directive
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); } } });
child directive
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'; }); } } });
view
<parent-directive> <button ng-click="parentctrl.toggle()">toggle message</button> <child-directive> <p>{{childctrl.someproperty}}</p> </child-directive> </parent-directive>
on scope you're watching, parent controller 'parentctrl' instead of 'parentcontroller', you're not watching property want be. following should work:
scope.$watch('parentctrl.someproperty', function () { controller.someproperty = parentcontroller.someproperty ? 'hello world!' : 'goodbye cruel world'; });
Comments
Post a Comment