Angular Change image src depending on class

2019-09-10 04:41发布

问题:

If image has 'loaded' class, i need to change image src to "{{item.preview2}}"

<div ng-repeat="item in items">
<img src="{{item.preview}}" class="grid-img" />
</div>

回答1:

directive('loaded', function(){
    return {
        restrict: 'C',
        link: function(scope){
             scope.item.preview = scope.item.preview2
        }

    }

})

and in html

<img ng-src="{{item.preview}}" class="grid-img" />


回答2:

In the case you describe I would just use ng-if to control what elements are rendered to the DOM. for example:

<img ng-if="item.loaded" src={{item.preview2}} class="grid-img-loaded"/>
<img ng-if="!item.loaded" src={{item.preview}} class="grid-img"/>

Hope this helps.