AngularJS share asynchronous service data between controllers -


i know issue has been asked several times in stackoverflow, couldn't find proper answer.

what need achieve able initiate asynchronous call in 1 controller , when result returns update $scope in other controller.

i understand should use shared service $http stuff, can't manage update other controller scope.

here code:

view

<div class="screens" ng-controller="framescontroller">    <div class="scroller scroll-pane" frames-scroll-pane>          <div class="overview">                {{frames}}                                </div>    </div> </div> 

service

 angular.module('brightspotapp.models', []).     factory('framesmodel', function($http,globals){        var api_path = 'clickard/getclickardbyid/';         var sharedservice = {};         sharedservice.getasync = function (id) {              sharedservice.frames = {};              $http.get(globals.serverurl + api_path + id).                 success(function (data, status, headers, config) {                     sharedservice.frames = data;                  }).error(function (data, status, headers, config) {                     console.log('http error');                 });          };          return sharedservice;        }); 

controllers

angular.module('brightspotapp.controllers', []).  /** * top menu controller */ controller('menucontroller', function($scope,framesmodel){     $scope.clicked = false;     $scope.toggle = function (item) {                $scope.clicked = !$scope.clicked;         if ($scope.clicked){                framesmodel.getasync(1);         }     };      $scope.itemclass = function(item) {         return $scope.clicked ? 'active' : undefined;     }; }). /**  * frames controller  */  controller('framescontroller', function($scope,framesmodel){      $scope.data = [];     $scope.frames = framesmodel;     }); 

this thing kind of works in sense updates $scope , consequently dom when async call returns.

but need achieve callback when async finishes (maybe $broadcast) notify frames controller , have control on returned data can manipulate before updating $scope , consequently dom.

assistance appreciated.

something this:

$http.get(globals.serverurl + api_path + id).then(function(result){     sharedservice.frames = result.data; }); 

if want getasync method return data when call has completed can use defer:

sharedservice.getasync = function (id) {      sharedservice.frames = {};     var defer = $q.defer();     $http.get(globals.serverurl + api_path + id).     then(function(result){         sharedservice.frames = result.data;         defer.resolve(result.data);     }).error(function (data, status, headers, config) {         console.log('http error');     });     return defer.promise; }; 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -