I'm trying to build a realtime application with AngularJS and a socket server. I try to follow John Papas Angular Styleguide
I have a factory called mainFactory:
...
socket.on('buylist', function(list) {
buylist = list;
$rootScope.$broadcast('buylist');
});
...
mainFactory.getBuylist = function () {
return buylist;
}
For the Controller I use the ControllerAs Syntax so I build a View Model variable. homeController:
var vm = this;
$scope.$on('buylist', function(e) {
vm.buylist = mainFactory.getBuylist();
console.log('TO TEST WHEN THE EVENT IS FIRED!')
});
And in the View:
<li ng-repeat="listitem in home.buylist">
...
</li>
This works fine BUT the view updates 2-5 seconds after the Event is fired. But I want the view to update instantly.
I got this to work by using the $scope instead of the vm and $apply() it on the event:
$scope.$on('buylist', function(e) {
$scope.buylist = mainFactory.getBuylist();
$scope.$apply();
});
And in the View:
<li ng-repeat="listitem in buylist">
...
</li>
SO everything is perfectly in realtime now BUT the styleguide says that I should try to avoid using the $scope whenever it's possible and use the ViewModel ControllerAs way instead. So what I'm looking for is a way to $apply the ViewModel or some other way to update the view instantly after the event is fired.