W
W
WhatIsHTML2017-02-01 21:32:52
Angular
WhatIsHTML, 2017-02-01 21:32:52

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
}]);

ControllerB
app.controller('ControllerB', ['$scope', '$rootScope', function($scope, $rootScope) {
  $scope.$on('hi', function(event, msg) {
    console.log('event fired!');
    $scope.increment = msg;
  });
}]);

Factory
app.factory('Factory', function($rootScope) {
  var self = this;
  self.send = function(msg) {
    console.log('Factory method run');
    $rootScope.$broadcast('hi', msg);
  }
  return self;
});

This is a simplified example, in reality I receive data from the server in the factory, they need to be transferred to scope.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RTW, 2017-02-01
@WhatIsHTML

For example, there is such a dirty hack) $timeout forces apply to the scope
jsfiddle.net/0p1p9x9e

_
_ _, 2017-02-01
@AMar4enko

When you fire an event in controller A, controller B has not yet been instantiated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question