2

In the example below, how can I run getData from another controller and have the scope variable in the view updated?

var app = angular.module('app', []);

app.factory('MyService', ['$http',function($http) {
    return {
       getData: function() {
          return $http.get('/api/endpoint');
       }
    };
}]);

app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
   MyService.getData().then(function(response){
     $scope.myVarialbe = response.data;
   });
}]);


app.controller('MyController2', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
  ///// ?????? How to get $scope.myVarialbe updated from the getData call?
   });
}]);
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

2 Answers2

1

Using $broadcast and $on :

$broadcast dispatches an event name downwards to all child scopes (and their children) and notify to the registered $Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified.

$on listen on events of a given type. It can catch the event dispatched by $broadcast

app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
   $scope.$on('variableChanged',function(event, value) { 
      $scope.myVariable = value;
   };
}]);


app.controller('MyController2', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
  MyService.getData().then(function(response){
     $scope.$broadcast('variableChanged', response.data);
  });
}]);
Community
  • 1
  • 1
Sajal
  • 4,359
  • 1
  • 19
  • 39
0
angular.module('app').controller('nav', function($scope,$http) {
 $rootScope.$on("CallMethodNavController", function(){
   $scope.navMethod();
}); 
$scope.navMethod=function(){
$http.get('/players').then(function(data) {
$scope.numOfPlayers = data.players.length;
}    
});
});

then in the second controller you call this method once a player is added like so:

    $rootScope.$emit("CallMethodNavController", {});