2017-05-26 57 views
1

我有一個從服務器獲取json並將其附加到列表的示例。如何等到ng-repeat完成循環?

腳本:

$http.get('/data/json/cities.json').then(function (res) { 
    if (res.status === 200) { 
     $scope.cities = res.data; 
    } 
}); 

HTML:

<li ng-repeat="(id, name) in cities" id="{{id}}"> 
    <a href="#" ng-bind="name"></a> 
</li> 

在那裏我卡住代碼:

if (res.status === 200) { 
    $scope.cities = res.data; 

    // from here 
    console.log($('li#NY').length); // 0 

    // waiting 1 second and try again 
    setTimeout(function() { 
     console.log($('li#NY').length); // 1 
    }, 1000); 
} 

JSON對象包含密鑰NY但我只能分配給1秒(或1秒)後的對象(li標籤id爲NY) onger)。

是否有另一種方法來知道什麼時候對象(在這種情況下爲$('li#NY'))已經創建成功,而不使用setTimeout

+0

什麼是你想要做什麼呢?代碼中不清楚爲什麼你需要這些信息。 – Karim

+0

嘗試使用'ng-repeat-end'指令 –

+0

@Karim什麼不清楚?該列表包含'$('li#NY')'對象,並且該對象將在獲取json之後創建。但是當我得到json時,我只能在1秒後分配給對象。 – Vayne

回答

2

您必須創建一個指令,請按照下面的代碼。

var module = angular.module('app', []) 
     .directive('onFinishRender', function ($timeout) { 
     return { 
      restrict: 'A', 
      link: function (scope, element, attr) { 
       if (scope.$last === true) { 
        $timeout(function() { 
         scope.$emit(attr.onFinishRender); 
        }); 
       } 
      } 
     } 
    }); 

然後在你的控制器,你可以用$上趕上它:

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) { 
    //you also get the actual event object 
    //do stuff, execute functions -- whatever... 
    console.log($('li#NY').length); // 1 
}); 

的HTML看起來像這樣:

<li ng-repeat="(id, name) in cities" id="{{id}}" on-finish-render="ngRepeatFinished"> 
    <a href="#" ng-bind="name"></a> 
</li> 
+1

它的工作原理。謝謝!你能解釋一下爲什麼我需要'$ timeout'嗎? – Vayne

+1

$ timeout確保在ng-repeated元素已完成渲染時執行它(因爲$ timeout將在當前摘要循環結束時執行 - 並且它也將在內部調用$ apply,與setTimeout不同)。所以在ng-repeat完成之後,我們使用$ emit來發送事件給外部作用域(同級和父級作用域)。 – LXhelili