2013-12-15 165 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 
      }); 

     };