1

控制器:角1:NG-重複拋出infdig錯誤

(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 Error: [$rootScope:infdig]

有人可以給我一個提示,爲什麼我得到這個錯誤?已經檢查過文檔,我不會在我的ng-repeat中調用函數,也不會在每次調用時生成一個新的Array。

+0

can you顯示'$ scope.jobs'值? –

+1

我認爲它會拋出錯誤,因爲'random'實際上是一個函數。嘗試沒有'orderBy' –

+0

$ scope.jobs = 陣列(20) 0:對象 1:對象 2:對象... ... – mrks

回答

1

我做了什麼來解決問題是在控制器中隨機排列Array而不是在視圖中排序:

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

如果你想ng-repeat數據隨機排序,你將不得不申請自己的過濾器是這樣的:

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

下次使用它,鑑於這樣的:

<tr ng-repeat='job in job | shuffle'> 
+0

仍然使用此過濾器拋出'[$ rootScope:infdig]'。 – mrks

+0

[這裏](https://plnkr.co/edit/Xy7AjgJQZYCOEOFEaNVD?p=preview)正在工作plunker –

+0

我想問題是,我有一個數組與多個對象。所以這就是爲什麼洗牌過濾器解決方案仍然無法正常工作。 – mrks