簡體   English   中英

如果滿足條件,則以角度顯示圖像

[英]Showing Images in Angular if condition is met

我有一個API調用,它返回一個數字。 根據該數字是多少,我希望顯示特定的圖像。

例如,如果:

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

只需很少的數學就可以輕松完成。 您可以使用Math.floor()計算要顯示的圖像的索引。 並使用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> 

請注意,在此示例中,100對應於您在問題中指定的間隔。 每次服務器發回新result ,必須重新計算$scope.computedIndex

根據API調用的響應,您可以在$ scope中設置圖像名稱,並在標記中顯示它。 這是一個偽代碼

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


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

等之間必須由條件運算符替換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM