javascript - Angular: Update service and share data between controllers -
i'm using service grab data 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 use these data in multiple 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 update data in every controller, when change $scope.message in controllera, doesn't fire change in controllerb.
edit: thing avoid using "$broadcast" , "$on".
any ideas?
here's jsfiddle: http://jsfiddle.net/victa/mclqd/
you can use $broadcast
broadcast event rootscope
, use $on
define listener listen specific 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 above solution before updated question. if don't want use $broadcast or $on, can share object via $rootscop
e 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; }); }
Comments
Post a Comment