Search code examples
angularjsangularjs-service

How do I set the value in my angularjs service?


I have created a service I want to use to set the value between controllers. I am using ng-model. Before my service I had this in my html:

<div class="col col-25">
        <a class="input" data-ng-keypad-input="numeric" tabindex="15" data-ng-model="fields.widthDefault" ng-change="updateROIWidths()">{{fields.widthDefault}}</a>
</div>

my fields were defined as such:

$scope.fields = {
  widthDefault  : 0

and my updateROIWidths was simply:

$scope.updateROIWidths = function(){
     $scope.fields.widthCurrent = Number($scope.fields.widthDefault);
};

However, now I need a service as I have to set the value from the default in other controllers. So, I made a service as such:

.service('DefaultValuesService', function() {
     this.defaultWidth = Number(0);

     this.getDefaultWidth = function() {
        return this.defaultWidth;
     };
     this.setDefaultWidth = function(w) {
        this.defaultWidth = Number(w);
     };
)

So what do I do in my html or js now to use the imputed default value to set the other values?


Solution

  • You need to inject the Service to both Controllers. You don't have any controller code here, but basically you will end up with something like

    .controller('controllerA', ['$scope', 'DefaultValuesService', function($scope, DefaultValuesService){
        $scope.fields = {
           widthDefault  : DefaultValuesService.defaultWidth
        }
    }]
    
    .controller('controllerB', ['$scope', 'DefaultValuesService', function($scope, DefaultValuesService){
        $scope.changeDefaultWidth = function(width){
           DefaultValuesService.defaultWidth
        }
    }]
    

    Note that due to the two-way binding feature of Angular, you dont need getters/setters.