2015-05-12 66 views
0

我想實現一個切換圖像[有3個圖像src],如果列表中的用戶有一個過濾器設置,問題是圖像src不會改變當我通過ajax重新加載候選對象時,因爲指令中的鏈接函數僅在實際頁面重新加載時觸發。Angular指令鏈接功能只能在頁面加載/重載時運行

我想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); 
     } 
    }; 
}); 

回答

1

在模板中使用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; 
    } 
} 
+0

完美,非常感謝! – ericsicons