響應..是正確的,但一個過濾器看起來適合你的使用情況:
你的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
你可以做更可讀:http://jsfiddle.net/F2dHM/ –
這是正確的,偏好的事:) – Mickael