Answer the question
In order to leave comments, you need to log in
How to update scope from factory/service?
In controller A I send a request through a factory method, and then I want to get the result to controller B. The problem is that if I run the factory method by default in controller A, immediately when it is initialized, then for some reason an event that starts $rootScope. $broadcast('hi', msg); does not come to controllerB, but only comes by pressing the button in controller A. I tried to update via $rootScope.apply() - it didn't help. How to update the scope in controller B without clicking on the button in controller A, but immediately when controller A starts?
Here is an example jsfiddle.net/ZvnbR/27
ControllerA
app.controller('ControllerA', ['Factory', '$scope', '$rootScope', function(Factory, $scope, $rootScope) {
$scope.add = function() {
Factory.send('new Message!'); //it works!
}
Factory.send('new Message!'); //doesnt' work
}]);
app.controller('ControllerB', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.$on('hi', function(event, msg) {
console.log('event fired!');
$scope.increment = msg;
});
}]);
app.factory('Factory', function($rootScope) {
var self = this;
self.send = function(msg) {
console.log('Factory method run');
$rootScope.$broadcast('hi', msg);
}
return self;
});
Answer the question
In order to leave comments, you need to log in
For example, there is such a dirty hack) $timeout forces apply to the scope
jsfiddle.net/0p1p9x9e
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question