2014-12-06 37 views
4

我想顯示的數據列表:顯示數據的列表 - 逐個

<li ng-repeat="d in list_of_data"> 
    <div class="line"> 
     {{ d }} 
    </div> 
</li> 

但是我想有外觀數據的每一行之間的停頓,所以使用這樣的代碼:

function MyCtrl($scope) { 
    $scope.list_of_data = []; 

    $scope.start = function() { 
     var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; 

     var addElement = function(i) { 
      alert(i); 
      $scope.list_of_data.push(a[i]); 
      if (i < a.length - 1) 
       setTimeout(function() { addElement(i+1); }, 1000); 

     } 

     addElement(0);      
    }; 
} 

但是,當我啓動代碼時,我在警報窗口中獲取所有數字(0..9),但頁面中只有一個DIV('1')。爲什麼?

這裏是一個JSFidlle

+0

ng-repeat是一個複雜的指令,可以執行多種操作。它爲集合中的每個元素創建一個子範圍。順便說一句,它有一個編譯功能和一個鏈接功能。我知道,鏈接函數是用來代替html模板字符串中的集合元素值。但是,有誰知道編譯函數做什麼? – 2014-12-06 11:28:20

+0

好吧,有沒有什麼辦法使用角度來完成我的任務? – demas 2014-12-06 11:29:16

+0

這個問題是一個非常有趣的問題...我很高興,它被提出... – 2014-12-06 11:33:47

回答

2

的問題是,功能進行消化週期,並查看未更新的執行的setTimeout第一個參數傳遞。最好使用setTimeout功能$timeout服務:

順便說一句,我看起來更好的解決方案與應用limitTo過濾器和增量限制與$間隔:

angular.module('myApp', []) 
 
    .controller('MyCtrl', function($scope, $interval) { 
 
    $scope.list_of_data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; 
 

 
    $scope.limit = 0; 
 

 
    $scope.start = function() { 
 
     $interval(function() { 
 
     $scope.limit += 1; 
 
     }, 1000, $scope.list_of_data.length); 
 
    }; 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="myApp"> 
 
    <div ng-controller="MyCtrl"> 
 
    <a href="#" ng-click="start()">press me</a> 
 
    <ul> 
 
     <li ng-repeat="d in list_of_data|limitTo:limit"> 
 
     <div class="line">{{d}}</div> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</div>

+0

感謝您的更好的解決方案。 – demas 2014-12-06 11:38:25

1

您可以使用$timeout或需要在addElment結束時撥打$scope.$digest()

var addElement = function(i) { 
     alert(i); 
     $scope.list_of_data.push(a[i]); 
     if (i < a.length - 1) 
      setTimeout(function() { addElement(i+1); }, 1000); 
     $scope.$digest(); 
    } 
1
var myApp = angular.module('myApp',[]); 


function MyCtrl($scope) { 
$scope.list_of_data = []; 

$scope.start = function() { 
    var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; 

    var addElement = function(i) { 
     alert(i); 
     $scope.list_of_data.push(a[i]); 
     **$scope.$apply($scope.list_of_data);** 
     if (i < a.length - 1) 
      setTimeout(function() { addElement(i+1); }, 1000); 

    } 

    addElement(0);      
}; 


} 

這裏是您的解決方案: - http://jsfiddle.net/bh9pvy04/5/

$應用將確保所有的車型已經使用新值更新。這將使列表更新,您將能夠看到該列表中的所有組件