0

Say I have a service that holds my data for a view or a few views and it looks like this.

angular.module('testApp').factory('MyService', MyService);

function MyService() {
    var data = {name: "Bill"};

    return {
        getData: getData
    };

    function getData() {
        return data;
    }
}

And in my controller I have it as this:

view.data = MyService.getData;

And I bind it to my model like this:

<input type="text" ng-model="myCtrl.data().name"/>

This binds the service's getter function to the ng-model and makes it so I never have to worry about updating my controller with service data and the other way around. My question, is there any negative effects to doing things this way? Performance effects with the $watcher calling numerous getters functions?

velouriam
  • 21
  • 2

1 Answers1

0

The way you are using looks working but that can cause a problem if your value is going to set on basis of any ajax / asynchronous.

But the more cleaner approach would be take using dot rule

Markup

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

Controller

view.data = MyService.data;

Service

angular.module('testApp').factory('MyService', MyService);

function MyService() {
    var data = {name: "Bill"};

    var otherOperation = function(){
        data.name = 'name has been changed.';
    };

    return {
        data: data,
        otherOperation: otherOperation
    };
};

By above approach any change in the service variable will reflect on the UI.

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thank you for the reply. I do have ajax calls in my service that would update the service variable, I just didn't include that in the simple example, but it does update the value and it works just fine. So that isn't an issue. I just wasn't sure if there would be performance impacts my way or not. – velouriam Aug 05 '15 at 21:18