gpt4 book ai didi

javascript - AngularJS 1.6 : Directive inside Directive Template works only first time

转载 作者:行者123 更新时间:2023-11-29 21:03:28 25 4
gpt4 key购买 nike

我有一个指令“头像”,它接受一个“用户”对象并显示用户的图像。

这很好用。

现在我有另一个指令“user”,它显示给定“user”对象的名称并在其模板中包含该指令。

这有效.. 第一次。

当我更新“用户”对象时,只有名称发生变化,图像(头像)没有变化。

我的问题:如何让它工作?

头像指令:

(链接函数:如果用户对象确实有一个“ext”属性,它会计算一个图像路径(“src”),否则它会显示一个标准的模板.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>

最佳答案

因为你的化身指令的代码只执行一个,在指令 init 上。如果你想更新更改,你应该将 $broadcast 事件添加到你的指令中,并在 $broadcast 事件上执行该代码。

有关$emit$broadcast$on 事件的更多信息,您可以查看这篇文章:Usage of $broadcast(), $emit() And $on() in AngularJS

像这样:

父 Controller

$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
})

关于javascript - AngularJS 1.6 : Directive inside Directive Template works only first time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com