0

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.