我正在尝试根据列表中的用户是否有过滤器集来实现切换图像[有3个图像src],问题是当我通过ajax重新加载候选对象时图像src不会改变,因为指令中的link函数仅在实际页面重新加载时触发。
我想要element.attr(' src' ...每次使用该指令时运行,并根据doneCondition属性设置正确的图像源
<div data-ng-repate="candidate in candidates">
<img-toggle
class="like_img"
doing='{{animation_img_src}}'
done='{{{done_img_src}}'
undo='{{{undo_img_src}}'
data-ng-click="ajaxButton($event, 'likeUser', {user_id: candidate.user_id})" // register filter on server
done-condition="{{candidate.filters.indexOf('liked') > -1}}"> // e.g. candidate.filters = 'liked|accessed|...'
</img-toggle>
</div>
指令JS
app.directive('imgToggle', function() {
return {
scope: {
class: '@',
done: '@',
doing: '@',
undo: '@',
alt: '@',
doneCondition: '@'
},
replace: true,
restrict: 'E',
template: '<img class="{{class}}" data-undo-src="{{undo}}" data-doing-src="{{doing}}" data-done-src="{{done}}" title="{{alt}}" alt="{{alt}}" />',
link: function(scope, element, atts) {
// Issue: link function runs once so if I reload the list via an ajax button and doneCondition changes the src is not being set updated
element.attr('src', scope.doneCondition === 'true' ? scope.done : scope.undo);
}
};
});
答案 0 :(得分:1)
在模板中使用$scope.getSrc()
并绑定到某个template: '<img ng-src="{{getSrc()}}"/>'
link: function(scope){
scope.getSrc = function(){
// your logic, for example:
return scope.doneCondition === 'true' ? scope.done : scope.undo;
}
}
函数。在该函数内部运行逻辑以确定实际显示的源:
{{1}}