Rihana
Rihana

Reputation: 443

Pass data to different controllers using Angularjs

I have the below code in one controller.

    $scope.DataModel= [];
    $scope.DataModelTexts= { buttonDefaultText: '' };

I will be using the same code in one more controller. Now instead of writing the same code in 2nd controller too, i want to know if there is a way to put this in a common code in some factory or service and use that in both the controllers. I have tried to read about factory and services and i am getting a bit confused of how to use any one of these in my scenario.

Any information would help me gain more knowledge about factory and services in angularjs. Thanks.

Upvotes: 0

Views: 32

Answers (2)

Sasang
Sasang

Reputation: 1281

You're on the right track, use can use a factory or a service to share code between controllers. Note that in angular services(and factories) are singletons; they are instantiated once when the app starts and then anytime you inject it into a controller, you are referencing the same instance. Consider the following code:

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

myApp.service('MyService', function() {
  let _someValue = 'Initial Value';
  this.setValue = function(value){
    _someValue = value;
  }
  this.getValue = function(){
    return _someValue;
  }
});

//First Controller Run
myApp.controller('ControllerA', function($scope, MyService) {
  MyService.getValue(); //Initial Value
  MyService.setValue("BRAND NEW VALUE!!!");
});

//Run after ControllerA
myApp.controller('ControllerB', function($scope, MyService) {
  MyService.getValue(); //BRAND NEW VALUE!!!
});

Her you'll see that MyService holds the state of someValue. ControllerA get MyService injected to it and can use the methods of that service to set a new value. Now for any subsequent call for that same state, like for instance by ControllerB, the updated value will be returned.

Upvotes: 1

Lance Whatley
Lance Whatley

Reputation: 2455

You can use the .config() or a run() blocks (good SO on these here: AngularJS app.run() documentation?) to bind these reused variables to $rootScope, then call them from $rootScope.DataModel and $rootScope.DataModelTexts from within your controllers or services (as long as you inject $rootScope into these controllers and services).

Upvotes: 0

Related Questions