I am trying to implement a toggle image [has 3 images src] based on if a user in a list has a filter set, the problem is the image src will not change when when I reloaded the candidates object via ajax because the link function in the directive is only being trigger on actual page reload.
我试图实现一个切换图像[有3个图像src]基于列表中的用户是否有过滤器集,问题是当我通过ajax重新加载候选对象时,图像src不会改变,因为链接功能在该指令仅在实际页面重新加载时触发。
I want element.attr('src' ... to run every time the directive is used and set the correct image source based on doneCondition attribute
我想要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>
Directive 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);
}
};
});
1 个解决方案
#1
1
Use ng-src
in the template and bind to some $scope.getSrc()
function. Inside that function run the logic to determine what source to actually display:
在模板中使用ng-src并绑定到某个$ 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
1
Use ng-src
in the template and bind to some $scope.getSrc()
function. Inside that function run the logic to determine what source to actually display:
在模板中使用ng-src并绑定到某个$ 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;
}
}