Angular: service update and data exchange between controllers

I use the service to capture some data from the API:

angular.module('myApp', []) .factory('myService', function($q, $timeout) { var getMessages = function() { var deferred = $q.defer(); $timeout(function() { deferred.resolve('Hello world!'); }, 2000); return deferred.promise; }; return { getMessages: getMessages }; }); 

And I use this data in several controllers.

 function ControllerA($scope, myService) { $scope.message = myService.getMessages(); $scope.updateMessage = function(){ $scope.message = 'Hello Max'; }; } function ControllerB($scope, myService) { $scope.message = myService.getMessages(); $scope.$watch('message', function(){ // 'Hello Max' }, true); } 

I would like to update the data in each controller, but when I change $ scope.message in ControllerA, it does not trigger the changes in ControllerB.

EDIT: The thing is, I would like to avoid using "$ broadcast" and "$ on".

Any ideas?

Here's jsfiddle: http://jsfiddle.net/Victa/McLQD/

+4
source share
1 answer

You can use $broadcast to broadcast the event to rootScope and use $on to define a listener to listen for that particular event.

 function ControllerA($scope, myService, $rootScope) { $scope.message = myService.getMessages(); $scope.updateMessage = function () { $scope.message = 'Hello Max'; $rootScope.$broadcast("HelloEvent", { msg: $scope.message }); }; } function ControllerB($scope, myService, $rootScope) { $scope.message = myService.getMessages(); $rootScope.$on("HelloEvent", function (event, message) { $scope.message = message.msg; }); } 

Updated:

I got the above solution before you updated your question. If you do not want to use $ broadcast or $ on, you can share the object via $rootScop e, like this

 function ControllerA($scope, myService, $rootScope) { $scope.message = myService.getMessages(); $scope.updateMessage = function () { $scope.message = 'Hello Max'; $rootScope.message = 'Hello Max'; }; } function ControllerB($scope, myService, $timeout, $rootScope) { $scope.message = myService.getMessages(); $rootScope.$watch('message', function (oldV, newV) { if(oldV === undefined && oldV === newV) return; $scope.message = $rootScope.message; }); } 

Demo using broadcast Demo without using broadcast

+8
source

Source: https://habr.com/ru/post/1496660/


All Articles