Reputation: 1495
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.
I want element.attr('src' ... to run every time the directive is used and set the correct image source based on doneCondition attribute
<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);
}
};
});
Upvotes: 0
Views: 1018
Reputation: 49590
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:
template: '<img ng-src="{{getSrc()}}"/>'
link: function(scope){
scope.getSrc = function(){
// your logic, for example:
return scope.doneCondition === 'true' ? scope.done : scope.undo;
}
}
Upvotes: 1