Question

I want to share data between two controllers using some factory method. The controller Ctrl1 belongs to the first DIV tag from which HTTP request is sent and data from server is received in streaming fashion. And in other DIV tag, I want to display that result as a list (ng-repeat) which keeps on updating as the HTTP result in first DIV gets updated (also, second DIV tag starts displaying results as soon as first DIV tag gets first response, and first DIV disappears). I know how to pass data between controllers one time (e.g. ng-click="pass()"), but not sure how to achieve this. I am looking for an answer which does not uses $rootScope.

Was it helpful?

Solution

You should create a service to contain the data, then inject the service in to each controller.

For example, lets define a 'myService' service with one property 'foo' equalling a string 'bar':

angular.module('myModule').service('myService', function() {
  this.foo = 'bar';
});

We can now use this in a controller as so:

angular.module('myModule').controller('MyCtrl', function($scope, myService) {
   $scope.myService = myService;
});

This is now accessible in the template as {{myService.foo}} or ng-model="myService.foo" as usual.

You can then use it in a second controller in a similar way, when you update the property 'foo' in either controller the changes will persist between controllers. This is because services in angular are singletons. What you're doing by defining a service like this is creating a singleton 'myService' which can be injected wherever you want and will always be instantiated only once.

If you need to watch for changes within the controller code, you can use $scope.$watch() as usual on myService.foo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top