简体   繁体   English

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

[英]Showing Images in Angular if condition is met

I have an API call which returns back a number. 我有一个API调用,它返回一个数字。 Depending on what that number is, I want a specific image to show. 根据该数字是多少,我希望显示特定的图像。

For example 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;
    });
  };

It can be done quite easily with a very tiny bit of math. 只需很少的数学就可以轻松完成。 You can use Math.floor() to compute the index of the image you want to show. 您可以使用Math.floor()计算要显示的图像的索引。 And use ng-if to show the correct image base on its index. 并使用ng-if根据索引显示正确的图像。

 angular .module('app', []) .controller('AppCtrl', function($scope) { $scope.images = [ { src : 'http://lorempixel.com/400/200/sports/1' }, { src : 'http://lorempixel.com/400/200/sports/2' }, { src : 'http://lorempixel.com/400/200/sports/3' }, { src : 'http://lorempixel.com/400/200/sports/4' }, { src : 'http://lorempixel.com/400/200/sports/5' } ]; $scope.result = 60; $scope.computedIndex = Math.floor($scope.result / 100); }); 
 <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> 

Note that in this example, 100 correspond to the interval you specify in your question. 请注意,在此示例中,100对应于您在问题中指定的间隔。 Every time your server send back a new result , you must recompute $scope.computedIndex . 每次服务器发回新result ,必须重新计算$scope.computedIndex

Depending on the response from the API call, you can set the image name in $scope and show it in tag. 根据API调用的响应,您可以在$ scope中设置图像名称,并在标记中显示它。 This is a pseudo code 这是一个伪代码

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


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

Etc. BETWEEN has to be replaced by conditional operator 等之间必须由条件运算符替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM