Rkaede
Rkaede

Reputation: 62

ng-repeat not working

I have a data structure that is generated by a function. It returns the the last 30 days in reverse order (as in 11, 10, 9, 8 etc.) as an array of objects.

function HoursCtrl($scope) {
    $scope.days = function () {
        var d = new Date();
        var result = [];

        for (i = 0; i < 31; i++) { 
            result.unshift({day:d.getDate() });     
            d.setDate(d.getDate() - 1);
        }
        return result;
    };
};

Here is the output of the function:

[ { day: 9 }, { day: 8 }, { day: 7 }, { day: 6 }, { day: 5 }, etc. ]

I am using ng-repeat to expose this data as a list:

<div ng-controller="HoursCtrl">
  <ul>
    <li ng-repeat="day in days">{{day.day}}</li>
  </ul>
</div>

The li elements are not being generated! What am I missing?

Upvotes: 1

Views: 1205

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219910

Instead of setting up a function as a method on the scope, just populate a days property on the scope:

function HoursCtrl($scope) {
    var d = new Date();
    $scope.days = [];
    for (var i = 0; i < 31; i++) { 
        $scope.days.unshift({day:d.getDate() });     
        d.setDate(d.getDate() - 1);
    }
};

For better performance, you might try looping in reverse and using push instead of unshift:

function HoursCtrl($scope) {
    var d = new Date();
    var counter = 31;
    var date = d.getDate();

    $scope.days = [];
    d.setDate(date - counter + 1);

    while ( counter-- ) {
        date = d.getDate();
        $scope.days.push({ day: date });     
        d.setDate(date + 1);
    }
};

Upvotes: 3

Ben Lesh
Ben Lesh

Reputation: 108471

You need to call it as a function.

ng-repeat="day in days()"

Upvotes: 3

Related Questions