0

I know that you're supposed to pass data between controllers via a service, but I don't know how to do it in this instance.

Assume you have ControllerA that has a method:

ControllerA.executePromise()

When the promise finishs I want to alert the service that it is done.

Then I want to alert ControllerB via the service that the promise from ControllerA is finished.

I know I can call a method after the promise finishes to tell the service that it is done, but how I can then instantly tell Controller B via the service that the promise is complete?

mnasc
  • 13
  • 2
  • 1
    Watching the service (or the value you are interested in) with $watch should do, as long as the call to executePromise is within the digest cycle. – Erpheus Sep 11 '14 at 14:34
  • 1
    You can use $broadcast from $rootScope so pass data from services to controllers (or anywhere really) http://stackoverflow.com/questions/14502006/scope-emit-and-on-angularjs – SoluableNonagon Sep 11 '14 at 15:37

1 Answers1

0

I recommend you always share data between your controllers (and also directives) using a Service/Factory and injecting it on both sides.

After that, just use your promise resolution function to update the service value.

app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: '',
      value2: ''
    }
  };
});

app.controller('FirstCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.directive('myDirective',['SharedService', function(SharedService){
  return{
    restrict: 'E',
    link: function(scope){
      scope.model = SharedService.sharedObject;
    },
    template: '<div><input type="text" ng-model="model.value"/></div>'
  }
}]);

Here is a plunkr showing how it can be done: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m

Fedaykin
  • 4,482
  • 3
  • 22
  • 32