我有一个json文件,其中包含服务的不同价格,具体取决于星期几(周末它更贵) 我使用angular来显示这些价格:
<div ng-repeat="arr in arrangementen | filter:'_1'" >Mon-Fri: € {{arr.prijs_ma_vr | number :2 }} </div>
<div ng-repeat="arr in arrangementen | filter:'_1'" >Sat: € {{arr.prijs_za | number :2 }} </div>
JSON:
{
"id": "_1",
"arrangement": "Vriendinnendag",
"prijs_ma_vr": 99.95,
"prijs_za": 103.95,
"prijs_zo": 104.95,
},
{
"id": "_2",
"arrangement": "Vipdag",
"prijs_ma_vr": 199.95,
"prijs_za": 205.95,
"prijs_zo": 209.95,
}
我想知道是否有更智能,更简单的方法来显示这些价格或来自这个json的其他元素。有时我只想显示一个元素(即一个价格)
(此网站中的示例:wellness example
答案 0 :(得分:1)
我会修改json并按照这样做:
{
"id": "_1",
"arrangement": "Vriendinnendag",
"prijs":[ 99.95, 103.95, 104.95 ],
“day”:['Mon-Fri','Sat','Sun']
},
{
"id": "_2",
"arrangement": "Vipdag",
"prijs":[ 199.95, 203.95, 204.95 ],
“day”:['Mon-Fri','Sat','Sun']
}
<div ng-repeat="arr in arrangementen | filter:'_1'" >
day[0] € {{arr.prijs[0] | number :2 }}<br>
day[1] € {{arr.prijs[1] | number :2 }}<br>
day[2] € {{arr.prijs[2] | number :2 }}
</div>
答案 1 :(得分:1)
我看到你已经接受了另一个答案,但我想给你另一个选择,即创建你自己的过滤器。
angular.module('demo',[])
.controller('MainCtrl', ['$scope', function($scope){
$scope.arr = [{ "id": "_1",
"arrangement": "Vriendinnendag",
"prijs_ma_vr": 99.95,
"prijs_za": 103.95,
"prijs_zo": 104.95, },
{ "id": "_2",
"arrangement": "Vipdag",
"prijs_ma_vr": 199.95,
"prijs_za": 205.95,
"prijs_zo": 209.95, }];
}])
.filter('weekdayPrice', function(){
return function(obj, id) {
var rtnval;
angular.forEach(obj, function(value){
if (value.id === id) {
return rtnval = value.prijs_ma_vr;
};
});
return rtnval;
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="MainCtrl">
<div>Weekday Price: {{arr | weekdayPrice: '_2' | number: 2 | currency: '€'}}</div>
</div>
&#13;
因此,此自定义过滤器将获取一个id,并仅返回其id与您传递到过滤器的ID匹配的对象的工作日价格。您可以像使用任何其他过滤器一样使用它,这样您就可以像内置过滤器一样将它们链接在一起,从而允许您在自定义工作日过滤器返回的值中添加其他过滤器,如货币或数字。
好处是您可以在整个应用程序中重复使用自定义过滤器;你不必改变你现在的json格式;更重要的是,你不必弄清楚项目的数组索引,这肯定容易出错。