我正在将电影的JSON列表加载到合并范围中,每部电影都有一个持续时间。 JSON代码段:
"duration": "PT157M"
此持续时间显示为字符串,其中数字是持续时间(以分钟为单位)。如何将数字转换为“ h:m”格式。例如:150 =“ 2:30”,以便在视图中显示?
我尝试将javascript与伪数据一起使用(以查看其是否有效),但我认为自定义过滤器更聪明?
.controller('MovieController', ['$scope', 'MovieFactory',
function($scope, MovieFactory) {
MovieFactory.get().then(function(response) {
$scope.movies = response.data;
// extract numbers from string
$scope.duration = 'PT150M';
$scope.regex = /\d+/g;
$scope.found = $scope.duration.match($scope.regex);
console.log($scope.found);
// convert number to hours:min
function timeConvert(n) {
$scope.num = n;
$scope.hours = ($scope.num / 60);
$scope.rhours = Math.floor($scope.hours);
$scope.minutes = ($scope.hours - $scope.rhours) * 60;
$scope.rminutes = Math.round($scope.minutes);
return $scope.finalResult = $scope.num + " min = " + $scope.rhours + " hour(s) and " + $scope.rminutes + " minute(s).";
}
console.log(timeConvert($scope.found));
});
}]);
查看:
<div ng-repeat="movie in movies">
<p>Duration must be here: {{movie.duration}} </p>
</div>
我看了很多文档,可惜没有运气。
答案 0 :(得分:0)
$scope.duration.match($scope.regex);
将匹配的数字作为具有一个元素的数组(在这种情况下为字符串“ 150”)返回。
您想要这样的东西:parseInt($scope.duration.match($scope.regex)[0]);