1

How to use a function in a ng-repeat values? For example, I have a date from order I have to calcculate a date diff so I need something like this: getDateDiffInDays({{order.dateOrder}}):

View:

<ul>
    <li ng-controller="Orders" ng-repeat="order in orders">
        {{order.product}} | {{order.dateOrder}} | getDateDiffInDays({{order.dateOrder}});
    </li>
</ul>

Controller:

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

Any Help

2 Answers 2

4

Response from CD.. is correct but a filter seems appropriate for your use case:

Your html:

<ul>
    <li ng-controller="Orders" ng-repeat="order in orders">
        {{order.product}} | {{order.dateOrder | getDateDiffInDays}}
    </li>
</ul>

Your application:

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

It is easy because you make a diff with current date, but if you need more complex diff, you can give parameter to your filter:

Your html:

<ul>
    <li ng-controller="Orders" ng-repeat="order in orders">
        {{order.product}} | {{order.dateOrder | getDateDiffInDays:today}}
    </li>
</ul>

Your application:

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

Now you have a reusable filter.

See this fiddle: http://jsfiddle.net/n78k9/2

Sign up to request clarification or add additional context in comments.

Comments

1

As @Mickael solution would be the right angular way, you can add your function to the scope,

Like:

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

and in your view call it like:

{{ getDateDiffInDays(order.dateOrder) }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.