8
I have a list with several data ($scope.messages
), but only some data interest me. After loading this list I make a foreach
and take only the data that interests me and give push
in a new list. That way:
angular.forEach($scope.messages, function(msgBD) {
if((msgBD.user == $scope.usuario && msgBD.destino == destino) || (msgBD.user == destino && msgBD.destino == $scope.usuario )){
$scope.msgs.push(msgBD);
}
});
$scope.messages = $scope.msgs;
But in the view mine ng-repeat
does not update alone
<ul class="media-list" ng-repeat="message in messages track by $index">
{{message.text}}
</ul>
When I use $scope.$apply
before the push works perfectly:
$scope.$apply(function(){
$scope.msgs.push(msgBD);
});
But give this console error:
"Error: [$rootScope:inprog] http://errors.angularjs.org/1.4.7/$rootScope/inprog? P0=%24apply
Is there any way to solve this problem? Or else treat this error?
UPDATE I created a Fiddle to better exemplify my problem.
- Open two browsers between two different names and Login
- Click the user who is online(The user q you created in the other browser)
- Send a message
- Nothing happens, so click the same user you sent it to a message again and you will see that the message is updated.
That’s the problem the message the list only "Updates" when I click again on the user I sent the message.
Fiddle
: http://jsfiddle.net/tjruzpmb/60/
Update 2
Example of the chat working perfectly after solution presented by @oOAkiraOo http://jsfiddle.net/sinkz/tjruzpmb/103/
NOTE: If many users are online, just click on clear users.
What is this variable of yours "fate"?
– MuriloMittmann
Dude, another question, in which event are you trying to update your array? at the time of rendering the screen? in some textbox that is changed?
– MuriloMittmann
In the event that sends the message, I’m riding a fiddle
– DiegoAugusto
@Techies by chance you’re wearing this exhibit inside some
ng-if
orng-show
? I remember that I once had a problem with this, the update only went into them with $apply(); but if used outside the if or show, it updates in real time, with no need for $apply() or $Digest().– celsomtrindade
@Techies from what I understand, you’re trying to create a chat, that’s it?
– celsomtrindade
$scope.apply()
makes asynchronous use of databind, calling the$scope.$digest()
, its use is recommended in a few cases, usually used along with the$timeout
orsetTimeout()
. For this reason, the event when it is called more than once, without time interval, gives this error. That is, it is slow.– Ivan Ferrer