I have two directives in parent and child relation , each one has link
implementation . The parent
set a scope
variant - name
, which is passed to the child
as attribute .
The order of the links execution is - firstly - the child
link and then the parent
link .
After the parent
link finish execution it broadcast to its child , but seems the child doesn't got this scope
changes yet .
Here Example -
var myAppModule = angular.module('myAppModule', []). directive('parent',function($parse){ return { restrict: 'E', link: function(scope) { scope.name = "Dan"; console.log("parent: My name is "+scope.name); scope.$broadcast("ready"); } } }) .directive('child',function($parse){ return { restrict: 'E', scope: { name: '=' }, link: function(scope) { scope.$on("ready",function () { console.log("child: My name is "+scope.name); }) } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script> <parent> <child name="name"> </child> </parent>
it logs -
parent: My name is Dan
child: My name is undefined
Why the child
didn't consider the change in name
after the broadcast
? Does it because the $digest
didn't called yet for this Angular turn ?
First, you cannot have a <child>
directive into the <parent>
one like this unless you use transclusion.
Then, dealing with events ( $broadcast
and $on
) to discuss from parent to child is not recommended, instead you could have a shared service, or even easier in this case just watch for the name
binding to be resolved.
See how it works on this snippet:
var myAppModule = angular.module('myAppModule', []). directive('parent',function($parse){ return { restrict: 'E', template: '<div>Parent: {{name}}<div ng-transclude></div></div>', transclude: true, link: function(scope) { scope.name = "Dan"; console.log("parent: My name is "+scope.name); } } }) .directive('child',function($parse){ return { restrict: 'E', scope: { name: '=' }, template: '<div>Child: {{name}}</div>', link: function(scope) { scope.$watch('name', function() { console.log("child: My name is "+scope.name); }); } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script> <div ng-app="myAppModule"> <parent> <child name="name"></child> </parent> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.