Angular 1: ng-repeat throws infdig error

2019-08-02 02:03发布

Controller:

(function(angular) {

    var app = angular.module('t2w');

    app.factory('httpq', function($http, $q) {
        return {
            get: function() {
                var deferred = $q.defer();
                $http.get.apply(null, arguments).success(deferred.resolve).error(deferred.resolve);
                return deferred.promise;
            }
        }
    });

    app.controller('JobsCtrl', ['$scope','httpq','baseUrl', function($scope, httpq, baseUrl) {

        httpq.get(baseUrl + '/jobs/json').then(function(data) {
            $scope.jobs = data;
        }).catch(function(data, status) {
            console.error('Error', response.status, response.data);
        }).finally(function() {
        });

        $scope.random = function() {
            return 0.5 - Math.random();
        };
    }]);

})(window.angular);

View:

...

<tbody>
    <tr ng-repeat="job in jobs | orderBy:random">
        <td class="jobtitle">
            <a href="#jobs/{{job._id}}">
                {{job.title}} m/w
            </a>
            <p>
                {{job.introText | limitTo: 150}}...
            </p>
        </td>
        <td>
            {{job.area}}
        </td>
    </tr>
</tbody>

...

JSON Response:

{
    "_id": "5880ae65ff62b610h4de2740",
    "updatedAt": "2017-01-19T12:17:37.027Z",
    "createdAt": "2017-01-19T12:17:37.027Z",
    "title": "Job Title",
    "area": "City",
    "introText": "Lorem Ipsum Sit Dolor",
    ...
}

Error:

angular.js:13920 Error: [$rootScope:infdig]

Can someone give me a hint why I get this error? Already checked the documentation and I do not call a function in my ng-repeat nor generate a new Array with each call.

2条回答
祖国的老花朵
2楼-- · 2019-08-02 02:22

If you want ng-repeat to sort data randomly you will have to apply your own filter like this:

.filter('shuffle', function() {
    return function(ary) {
        return _.shuffle(ary);
    }
});

next use it in view like this:

<tr ng-repeat='job in job | shuffle'>
查看更多
相关推荐>>
3楼-- · 2019-08-02 02:27

What I did to resolve the problem is to sort the Array randomly in the controller and not in the view:

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

$scope.jobs = shuffle($scope.jobs);
查看更多
登录 后发表回答