在ng-repeat中显示每个项目的特定图像

时间:2015-03-16 16:34:06

标签: angularjs

我有一个ng-repeat,其中显示了一个体育列表,并且在我想要显示特定图像的每个体育名称旁边。我想知道如何为每项运动展示正确的png。我怎么能让它知道要显示什么图像?这是代码的样子。

<div ng-if="sport.leagues.length && sport.checked"
      ng-repeat="sport in sports">
      <ion-list class="list">
        <div class="item">
          <img src="" class="sport-image"> <!--Heres where img shoud be-->
          <span>{{sport.name}}</span>
        </div>
      </ion-list>
</div>

4 个答案:

答案 0 :(得分:1)

您应该使用ng-src而不是src,以便您可以将变量传递给它,表示要显示的当前图像,而不会在角度表达式未被解析时冒错误404又:

<img ng-src="{{sport.image}}" />

在JS部分中,您只需要在控制器中

$scope.sport = {image: "http://myServer.com/mySuperSportImage.jpg"};

请注意,此示例并未处理集合以简化 这确保了绑定。

答案 1 :(得分:1)

我想你想要一个基于一个键的图像(比如运动名称)。您可以使用键维护控制器中的javascript对象,因为名称和值可以是图像的URL

  

obj = {football:&#39; myurl&#39;}

并将此对象用作

<div ng-if="sport.leagues.length && sport.checked"
  ng-repeat="sport in sportsFilter = ( sports | sportsFiltered:query )">
  <ion-list show-delete="sport.showStars"
            class="list">
    <div class="item">
      <img ng-src="{{obj[sport.name]}}" class="sport-image"> <!--Heres where img shoud be-->
      <span>{{sport.name}}</span>
    </div>

答案 2 :(得分:1)

您应该为图像创建一个对象属性:

// HTML

<div ng-app="myApp" ng-controller="MyCtrl">
    <div ng-if="sport.leagues.length && sport.checked"
      ng-repeat="sport in sports">
        <div class="item">
            <img width="30" height="30" src="{{ sport.im }}" class="sport-image"> <!--Heres where img shoud be-->
            <span>{{sport.name}}</span>
        </div>
    </div>
</div>

// JS

angular.module('myApp',[])
  .controller('MyCtrl', function($scope) {    

    $scope.sport = {
        leagues: ['premier', 'championship'],
        checked: true
    };

    $scope.sports = [
        {
            name: 'soccer', 
            im: 'http://upload.wikimedia.org/wikipedia/en/e/ec/Soccer_ball.svg'
        },
        {
            name: 'basketball',
            im: 'http://upload.wikimedia.org/wikipedia/commons/7/7a/Basketball.png'
        }
    ];
});

看到这个小提琴: http://jsfiddle.net/uxu21n4v/1/

答案 3 :(得分:0)

<img ng-src="http://www.gravatar.com/avatar/{{sport.imageLocation}}" class="sport-image"/>

参考:https://docs.angularjs.org/api/ng/directive/ngSrc

相关问题