如果满足条件,则以Angular显示图像

时间:2015-09-30 03:55:40

标签: javascript angularjs

我有一个API调用,它返回一个数字。根据该数字的不同,我希望显示一个特定的图像。

例如:if:

0 to 100:   icon1.png
101 to 200: icon2.png
201 to 300: icon3.png
301 to 400: icon4.png
401 to 500: icon5.png
501 to 600: icon6.png

$scope.result = 60

How would I get the result to show icon1.png?

// index.html
{{results.[0].id}} // this shows up as a number and i would like to have the image rendered here
{{results.[1].id}}
{{results.[2].id}} 

// app.js
$scope.submit = function () {
  var url = 'http://api.com';
  $http.get(url)
    .then(function (response) {
      $scope.results = response;
    });
  };

2 个答案:

答案 0 :(得分:2)

只需很少的数学运算就可以轻松完成。您可以使用Math.floor()来计算要显示的图像的索引。并使用ng-if在其索引上显示正确的图像。



<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="AppCtrl">
    <img ng-repeat="image in images" ng-if="computedIndex === $index" src="{{ image.src }}">
  </div>
</div>
&#13;
result
&#13;
&#13;
&#13;

请注意,在此示例中,100对应于您在问题中指定的间隔。每次您的服务器发回新的$scope.computedIndex时,您都必须重新计算{{1}}。

答案 1 :(得分:0)

根据API调用的响应,您可以在$ scope中设置图像名称并将其显示在标记中。这是一个伪代码

if ($scope.result BETWEEN 1 TO 100)
    $scope.img= ="icon1.png"


if ($scope.result BETWEEN 101 TO 200)
    $scope.img= ="icon2.png"

等。 BETWEEN必须由条件运算符

替换
相关问题