2013-12-15 216 views
13

我使用ng-repeat呈現html table。我的控制器看起來像這樣:AngularJS ngRepeat更新模型

app.controller("fooCtrl", function($scope, WebSocket) { 
    $scope.foo = [ ... ]; 

    WebSocket.start(function(data) { 
    // this is a callback on websocket.onmessage 
    // here is a for loop iterating through $scope.foo objects and updating them 
    }); 
}); 

正如你所看到的,我定期更新$scope.foo陣列。然而,我的觀點是構建像這樣:

<tr ng-repeat="item in foo"> 
    ... 
</tr> 

的問題是,當我更新foo,它不會重新渲染我的表用新的數據。

我該如何解決這個問題?

+0

嗨,你是否知道如何將一個項目添加到ng-repeat列表的頂部?我可以更新我的列表 - 新的項目被渲染,但它到達列表的底部。 – lulu88

回答

25

你包裹在

$scope.$apply(function() { 
    // update goes here 
}); 

更新?這應該可以解決問題。

+4

此外,您可以在更改後放置$ scope。$ apply()。 – WMios

3

你可能需要調用$apply()給力的角度做一個摘要週期,當你更新列表,如:

WebSocket.start(function(data) { 
    $scope.$apply(function(){ 
     /* your stuff goes here*/ 
    }); 
    }); 
+0

給我一個錯誤:'Uncaught TypeError:Object# has no method'apply'' –

+0

@JanNetherdrake請看這篇文章的描述:http://jimhoskins.com/2012/12/17/angularjs-and-apply .html –

+0

@JanNetherdrake它是'$ apply',而不是'apply'。 – lex82

0

下面的代碼爲我工作,當你從插座得到消息,你只需要綁定$ apply()函數

socket.on = function (e) { 

      $scope.$apply(function() { 
       // update you UI over here 
      }); 

     };