2014-01-22 8 views
1

如何在ng-repeat值中使用函數?例如,我有個約會從訂單我不得不calcculate日期差異,所以我需要的東西是這樣的:getDateDiffInDays({{order.dateOrder}})在ng-repeat中使用函數

查看:

<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)); 
    } 
}]); 

任何幫助

回答

4

響應..是正確的,但一個過濾器看起來適合你的使用情況:

你的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

+0

你可以做更可讀:http://jsfiddle.net/F2dHM/ –

+1

這是正確的,偏好的事:) – Mickael

1

作爲@Mickael解決方案N將是正確的角度來說,您可以將功能添加到範圍,

像:

$scope.getDateDiffInDays = function() { . . . } 

,並在您的視圖調用它:從CD

{{ getDateDiffInDays(order.dateOrder) }}