如何在ng-repeat值中使用函数?例如,我有一个订单日期我必须计算日期差异,所以我需要这样的东西:getDateDiffInDays({{order.dateOrder}})
:
查看:
<ul>
<li ng-controller="Orders" ng-repeat="order in orders">
{{order.product}} | {{order.dateOrder}} | getDateDiffInDays({{order.dateOrder}});
</li>
</ul>
控制器:
.controller('Orders',function($scope){
$scope.today = new Date();
this.getDateDiffInDays = function(dateParam) { //dateParam is a timestamp
var t1 = today.getTime();
return parseInt((t1-dateParam)/(24*3600*1000));
}
}]);
任何帮助
答案 0 :(得分:4)
来自CD的响应..是正确的,但过滤器似乎适合您的用例:
你的HTML:
<ul>
<li ng-controller="Orders" ng-repeat="order in orders">
{{order.product}} | {{order.dateOrder | getDateDiffInDays}}
</li>
</ul>
您的申请:
var app = angular.module('myApp', []);
app.filter('getDateDiffInDays', function() {
return function(myDate) {
var t1 = new Date().getTime();
return parseInt((t1 - myDate) / (24 * 3600 * 1000), 10);
};
});
app.controller('Ctrl', ['$scope', function($scope) {
$scope.orders = [
{ product: 'foo', dateOrder: new Date(2014, 0, 1) },
{ product: 'bar', dateOrder: new Date(2013, 0, 1) }
];
}]);
这很简单,因为您使用当前日期制作差异,但如果您需要更复杂的差异,则可以为过滤器提供参数:
你的HTML:
<ul>
<li ng-controller="Orders" ng-repeat="order in orders">
{{order.product}} | {{order.dateOrder | getDateDiffInDays:today}}
</li>
</ul>
您的申请:
var app = angular.module('myApp', []);
app.filter('getDateDiffInDays', function() {
return function(myDate, baseDate) {
// Second parameter can be optional
var t1 = (baseDate || new Date()).getTime();
return parseInt((t1 - myDate) / (24 * 3600 * 1000), 10);
};
});
app.controller('Ctrl', ['$scope', function($scope) {
$scope.today = new Date();
$scope.orders = [
{ product: 'foo', dateOrder: new Date(2014, 0, 1) },
{ product: 'bar', dateOrder: new Date(2013, 0, 1) }
];
}]);
现在你有了一个可重复使用的过滤器。
看到这个小提琴:http://jsfiddle.net/n78k9/2
答案 1 :(得分:1)
由于@Mickael解决方案是正确的角度方式,您可以将您的功能添加到范围,
喜欢:
$scope.getDateDiffInDays = function() { . . . }
并在您的视图中称之为:
{{ getDateDiffInDays(order.dateOrder) }}