我在父子关系中有两个指令,每个指令都有link
实现。 parent
设置scope
变体-name
,该变体作为属性传递到child
。
链接的执行顺序是-首先-child
链接,然后是parent
链接。parent
链接完成执行后,会广播给其子级,但似乎子级尚未更改此scope
。
这里的例子-
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>
它记录-
parent: My name is Dan
child: My name is undefined
为什么
child
在name
之后不考虑broadcast
中的更改?是否是因为$digest
尚未在此Angular转弯中调用? 最佳答案
首先,除非使用转写,否则无法在<child>
指令中加入<parent>
指令。
然后,不建议处理事件($broadcast
和$on
)以从父级到子级进行讨论,相反,您可以使用共享服务,或者在这种情况下甚至更简单,只需注意解决name
绑定。
查看此代码段的工作方式:
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>