AngularJS 1.6:Directive模板内指令模板只工作第一次
问题描述:
我有一个指令“头像”,它采取一个“用户”的对象,并显示用户的图像。AngularJS 1.6:Directive模板内指令模板只工作第一次
这工作正常。
现在我有另一个指令'用户',它显示给定'用户'对象的名称,并包括使用其模板的指令。
这是有效的。第一次。
当我更新'用户'对象时,只有名称改变,图像(头像)不会改变。
我的问题:我如何使它工作?
头像指令:
(链接函数:如果用户对象并有一个“分机”属性,它计算图像路径(“SRC”),否则它会显示一个标准template.jpeg)
directive('avatarSmall', function() {
return {
restrict: "E",
replace: true,
templateUrl: "scripts/directives/avatar/small.html",
link: function(scope, element, attrs) {
var r = "images/avatars/";
var ext = scope.user.ext;
r += ext != undefined && ext.length >= 3 ? scope.user.ID + "." + ext : "template.jpeg";
scope.src = r;
},
scope: {
user: '='
}
}
})
头像模板:
<div class="circle-wrapper-small">
<img class="circle-img-small"
ng-src="{{src}}">
</div>
用户指令:
directive('user', function($compile) {
return {
restrict: "E",
replace: true,
templateUrl: "scripts/directives/user/template.html",
scope: {
user: '='
}
}
})
用户模板:
<div>
<div class="media-left">
<avatar-small user="user" />
</div>
<div class="media-body">
<h4 class="media-heading">{{user.name}} {{user.surname}}</h4>
</h5>
</div>
</div>
答
因为你的头像指令的代码执行唯一的,在指令初始化。如果您想更新更改,则应该向您的指令提供$broadcast
事件,并在$broadcast
事件中执行该代码。
欲了解更多信息有关$emit
,$broadcast
和$on
事件中,你可以浏览这个帖子:Usage of $broadcast(), $emit() And $on() in AngularJS
事情是这样的:
父控制器
$scope.user = {
// object properties
}
// watch "$scope.user" for changes
$scope.$watch('user', function(newVal, oldVal){
if(newVal !== oldVal) {
// send new "$scope.user" to your directive
$scope.$broadcast('userObjChanged', $scope.user);
}
}, true);
和你的指令内
// catch event from parent's controller with new user object
$scope.$on('userObjChanged', function(event, data) {
console.log(data); // here is the new user object from parent's scope
})
感谢您的好评,今天我学到了一些新东西!此外(对于其他用户也有同样问题),我用ng-include ='avatar-template-source-source'替换'',但结果是一样的,它只在第一次运行。 –
MehmetGunacti
我很高兴你觉得它有帮助。干杯! –