问题
I use ng-repeat
to render a html table
. My controller looks like so:
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
});
});
As you can see, I am updating the $scope.foo
array periodically. However, my view is constructed like so:
<tr ng-repeat="item in foo">
...
</tr>
The problem is, when I update foo
, it doesn't re-render my table with new data.
How would I go about this problem?
回答1:
Did you wrap the update in
$scope.$apply(function() {
// update goes here
});
? This should solve the problem.
回答2:
You probably need to call $apply()
to force angular to do a digest cycle when you update the list, like:
WebSocket.start(function(data) {
$scope.$apply(function(){
/* your stuff goes here*/
});
});
回答3:
Following code work for me, Whenever you get message from socket you just need to bind your code inside $scope.$apply() function
socket.on = function (e) {
$scope.$apply(function () {
// update you UI over here
});
};
来源:https://stackoverflow.com/questions/20599877/angularjs-ngrepeat-update-model