javascript - Angular: share asynchronous service data between controllers -
i "bind change" of asynchronous data between controllers.
i know it's bit confusing hope possible.
in following example, if write in input, works great: http://jsfiddle.net/victa/9nrs9/
html:
<div ng-app="myapp"> <div ng-controller="controllera"> controllera.message = {{message.hello}}<br/> <input type="text" ng-model="message.hello"/> </div> <hr/> <div ng-controller="controllerb"> controllerb.message = {{message.hello}}<br/> <input type="text" ng-model="message.hello"/> </div> </div>
js:
angular.module('myapp', []) .factory('myservice', function($q, $timeout) { var message = { hello: 'hello world' }; return { getmessage : function(){ return message; } }; }) function controllera($scope, myservice) { $scope.message = myservice.getmessage(); } function controllerb($scope, myservice) { $scope.message = myservice.getmessage(); }
but let's grab data server. "link" data in previous example. http://jsfiddle.net/victa/j3kjj/
the thing avoid using "$broadcast"/"$on" or sharing object in $rootscope.
html:
<div ng-app="myapp"> <div ng-controller="controllera"> controllera.message = {{message.hello}}<br/> <input type="text" ng-model="message.hello"/> </div> <hr/> <div ng-controller="controllerb"> controllerb.message = {{message.hello}}<br/> <input type="text" ng-model="message.hello"/> </div> </div>
js:
angular.module('myapp', []) .factory('myservice', function($q, $timeout) { var message = {}; return { getmessage : function(){ var deferred = $q.defer(); $timeout(function() { message.hello = 'hello world!'; deferred.resolve(message); }, 2000); return deferred.promise; } }; }) function controllera($scope, myservice) { $scope.message = myservice.getmessage(); } function controllerb($scope, myservice) { $scope.message = myservice.getmessage(); }
thanks help.
victor
you returning promise
in factory
's return object , not actual object itself. in scope should wait promise mend concrete object assign $scope.message
example:
function controllera($scope, myservice) { myservice.getmessage().then(function(obj){ $scope.message=obj }); }
i changed fiddle might answer, see this fiddle
Comments
Post a Comment