如果条件满足,在Angular中显示图像
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"
等。BETWEEN必须用条件运算符
相关文章:
- 从桌面读取python文件时高亮显示代码
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何在生成下载文件时显示加载动画
- React重新渲染但未显示正确的组件
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 音频控件在mouseover上显示,在mouseout上淡出
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 显示5秒后隐藏潜水
- 画廊图像未显示
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 高亮显示时编辑文本大小和颜色
- 有时数据是't显示在浏览器中
- 当鼠标悬停在文本中的单词上时显示警报
- 角度图表;t显示在我的页面中
- 显示图工具提示显示x轴的最后日期值,而不是当前值