1

控制器:

(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);

看法:

...

<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响应:

{
    "_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",
    ...
}

错误:

angular.js:13920 错误:[$rootScope:infdig]

有人可以提示我为什么会收到此错误吗?已经检查了文档,我没有在我的 ng-repeat 中调用函数,也没有在每次调用时生成一个新数组。

4

2 回答 2

2

如果您想ng-repeat对数据进行随机排序,则必须应用您自己的过滤器,如下所示:

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

接下来在这样的视图中使用它:

<tr ng-repeat='job in job | shuffle'>
于 2017-02-15T14:37:23.817 回答
1

我为解决这个问题所做的是在控制器中而不是在视图中随机排序数组:

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);
于 2017-02-23T13:53:27.423 回答