请帮助,我有一个Angular方法,我试图从对象中获取值并获得结果看起来" 周一至周五:0800-1600 & #34;
$scope.ourHours = {
services: [{
title: "Office hours",
phone: "1-800-123-1234",
hours: [
{day:'Monday',open:'0800',close:'1800'},
{day:'Tuesday',open:'0800',close:'1800'},
{day:'Wednesday',open:'0800',close:'1800'},
{day:'Thursday',open:'0800',close:'1800'},
{day:'Friday',open:'0800',close:'1800'}
]
}]
};
答案 0 :(得分:1)
我会跟踪前几天,如果时间匹配,请将它们分组:
function getHoursText(hours){
var arr = [], txt = [];
for(var i=0; i<hours.length; i++){
if(arr.length &&
(arr[0].open !== hours[i].open || arr[0].close !== hours[i].close)
){
txt.push(arrayToText(arr));
arr = [];
}
arr.push(hours[i]);
}
txt.push(arrayToText(arr));
return txt.join('\n');
function arrayToText(arr){
var str;
if(!arr.length){ return ""; }
str = arr[0].day;
if(arr.length > 1){ str += '-' + arr.pop().day; }
str += ': ' + arr[0].open + '-' + arr[0].close;
return str;
}
}
/*
* Example usage
*/
var hours = [
{day:'Monday',open:'0800',close:'1500'},
{day:'Tuesday',open:'0800',close:'1800'},
{day:'Wednesday',open:'0800',close:'1800'},
{day:'Thursday',open:'0800',close:'1800'},
{day:'Friday',open:'0800',close:'1500'}
];
console.log( getHoursText(hours) );
答案 1 :(得分:0)
这个怎么样?
angular.module('app', [])
.filter('hours', function() {
return function(item) {
return item.substr(0,2) + ":" + item.substr(2,2);
}
})
.controller('ShopHours', function ShopHours($scope) {
$scope.ourHours = {
services: [{
title: "Office hours",
phone: "1-800-123-1234",
hours: [
{day:'Monday',open:'0800',close:'1800'},
{day:'Tuesday',open:'0800',close:'1800'},
{day:'Wednesday',open:'0800',close:'1800'},
{day:'Thursday',open:'0800',close:'1800'},
{day:'Friday',open:'0800',close:'1800'}
]
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ShopHours">
<div ng-repeat="serv in ourHours.services">
<h3>{{serv.title}}</h3>
<p>Phone: {{serv.phone}}</p>
<div>Hours:
<ng-repeat ng-repeat="hours in serv.hours">
<p><b>{{hours.day}}:</b> from {{hours.open | hours}} to {{hours.close | hours}}</p>
</ng-repeat>
</div>
</div>
</div>