Search code examples
angularjsangularjs-scopeangularjs-service

Is there a good way to ensure that the changes to Scope variables that occur by two-way binding are reflected in the corresponding service variable?


Consider the code:

app.service('myService', function() {
    var _name = '';

    this.getName = function() {
        return _name;
    }

    this.setName = function(name) {
        _name = name;
    }
});

With the controller assigning the scope variable:

$scope.name = myService.getName();

and I have used the name for data binding.

<input type="text" ng-model="name" />

How do I ensure that any changes I have done to name from the input box are reflected in the service variable _name. I know $watch and calling myService.setName is an option, but I would like to avoid it because I have a lot of variables like that and I would like to retain them when I change the view.

Use case could be: A multi-view signup form, where each view contains a certain number of entries and moving to the next page would ask to enter more information. (Yes, I do not want to call myService.setName on clicking the next button either :)...)


Solution

  • Wrap your string into an object:

    app.service('myService', function() {
        var person = {
          name: ''
        }
    
        this.getPerson = function() {
            return person;
        }
    });
    
    $scope.person = myService.getPerson();
    
    <input type="text" ng-model="person.name" />