2017-03-04 65 views
0

對於一些未知的原因NG重複從NG-路線加載的模板文件上重複了太多次:NG重複循環的次數太多

angular 
    .module('myApp', [ 
    'ngAnimate', 
    'ngCookies', 
    'ngResource', 
    'ngRoute', 
    'ngSanitize', 
    'ngTouch' 
    ]) 
    .config(function ($routeProvider) { 
    $routeProvider 
     .when('/items/item1', { 
     templateUrl: 'items/item-review.html', 
     controller: 'ItemController', 
     controllerAs: 'myCtrl' 
     }) 
     .otherwise({ 
     redirectTo: '/' 
     }); 

    }); 

HTML:

<div class="reviewItem" ng-repeat="reviewItem in myCtrl.prop"> 

    <div class="row"> 
     <div>{{reviewItem.name}} </div> 
    </div> 

</div> 

它給我5個循環,而不是物體的具有在JSON文件2個對象的陣列中的量:

[{ 
    "item": { 
     "name": "content", 
     "name2": "content2" 
    } 
}, { 
    "item": { 
     "name": "content", 
     "name2": "content2" 
    } 
}] 

控制器是這樣THI S:

angular.module('dbreviewsApp') 
    .controller('ItemController', function($scope, $http) { 

    var myCtrl = this; 
    myCtrl.prop=[]; 

     $http.get('items.json') 
     .then(function(response) { 

      myCtrl.prop = response; 

     }, function(response) { 

      //Second function handles error but there is no error during the get request 

     }); 

}); 
+0

remove myCtrl.prop = [];並嘗試 –

+1

請提供小提琴。 「ng-repeat循環太多次」和「5次循環」是什麼意思? –

+0

從你在這裏給出的東西中,有兩件事情需要改變......將'myCtrl'改爲'$ scope.myCtrl',並在HTML中將'{{reviewItem.name}}'改爲'{{reviewItem。 item.name}}'。你怎麼知道它循環5次,即使沒有這些變化,它也不應該循環一次?請提供小提琴或發佈完整的代碼 – Nishant123

回答

0

問題是與你正在使用分配迴響應數據的技術:

$http.get('items.json') 
     .then(function(response) { 

      myCtrl.prop = response; //<-- This is the problem. 

      // Comment/remove the upper line and write it like 
      myCtrl.prop = response.data; // <-- Correct technique. 

     }, function(response) { 

      //Second function handles error but there is no error during the get request 

     }); 

代替myCtrl.prop = response;,使用data屬性賦值;像myCtrl.prop = response.data;

,並闡明爲什麼你的ng-repeat是循環5次是因爲response對象包含5個屬性即data, status, headers, config, statusText

0

問題是與myCtrl.prop = response;它應該是myCtrl.prop = response.data;。 請找工作Plunker

var myCtrl = this; 
    myCtrl.prop = []; 

    $http.get('items.json') 
    .then(function(response) { 

     myCtrl.prop = response.data; 
     console.log(myCtrl.prop); 

    }, function(response) { 

     //Second function handles error but there is no error during the get request 

    }); 
0

當您在響應中使用$資源,那麼數據,但如果使用$ HTTP數據,然後在你的response.data

myCtrl.prop = response.data; 
0

謝謝你幫我解決。 顯然問題出在傳遞的對象 - 默認情況下它有5個屬性:config, data, headers, status, statusText,因此5次重複,「數據」定位丟失。

在ng-repeat中添加.data:myCtrl.prop.data解決了這個問題。 myCtrl.prop = response.data;正在工作。