提问者:小点点

使用AngularJs在td中基于条件/数字添加Span图标/字形图标/图形


我正在尝试添加span图标/字形图标使用angular在td之前的国家,我已经使用了以下代码这样做,但我需要做更好的方式动态。需要你的帮助。

    $scope.countries = [
        {name: 'Australia', rating: 0, other: "lorem ipsum"},
        {name: 'India', rating: 1, other: "lorem ipsum"},
        {name: 'Canada', rating: 3, other: "lorem ipsum"},
        {name: 'Mexico', rating: 2, other: "lorem ipsum"},
        {name: 'UK', rating: 4, other: "lorem ipsum"},
        {name: 'Germany',rating: 2, other: "lorem ipsum"},
        {name: 'USA',rating: 1, other: "lorem ipsum"}
    ];

<tr ng-repeat="country in countries">
    <td>
        <span ng-if="country.rating == 1">
                <span class="glyphicon glyphicon-star"></span>
         </span>
        <span ng-if="country.rating == 2">
                <span class="glyphicon glyphicon-star"></span>
                <span class="glyphicon glyphicon-star"></span>
         </span>
        <span ng-if="country.rating == 3">
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
      </span>
        <span ng-if="country.rating == 4">
        <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
      </span>
        <span>
            {{ country.name}}
        </span>
    </td>
    <td>{{country.other}}</td>
</tr>

共3个答案

匿名用户

创建一个函数来获得一个数组星形数字,然后在ng-repeat上使用它

$scope.getArrayNumber = function(num) {
   return new Array(num);   
};


<tr ng-repeat="country in countries">
   <td>
      <span ng-repeat="star in getArrayNumber(country.rating) track by $index">
          <span class="glyphicon glyphicon-star"></span>
      </span>
      <span>
          {{country.name}}
      </span>
   </td>
</tr>

匿名用户

基于@koga提供的答案,另一种做法是不使用轨道通过:

$scope.getArrayNumber = function(num) {
    var array = [];
    for (var i = null; i < num; i++) {
        array.push(i);
    };
   return array;   
};

<tr ng-repeat="country in countries">
   <td>
      <span ng-repeat="star in getArrayNumber(country.rating)">
          <span class="glyphicon glyphicon-star"></span>
      </span>
      <span>
          {{country.name}}
      </span>
   </td>
</tr>

匿名用户

您可以使用第二个ng-repeat:

<span ng-repeat="idx in country.rating track by $index" class="glyphicon glyphicon-star"</span>