Skip to content Skip to sidebar Skip to footer

General-purpose Gettersetter In Angularjs

Documentation for ngModel has an example for getterSetter: angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'B

Solution 1:

It seems to me that you don't actually need to use a getterSetter. Creating a separate model for handling users would be more useful. One way to do this is to create an Angular service. Here's a contrived example:

// I'm using a separate module, but you don't have to
angular.module('user').factory('User', function() {

    functionUser(name) {
        this.name = name;
    }

    returnUser;

});

Now if we go back to your code:

angular.module('getterSetterExample', ['user'])
  .controller('ExampleController', ['$scope', 'User', function($scope, User) {
      $scope.user = new User('Brian');
  }]);

I've injected my "user factory" to the controller and then use it to create the user model. You can inject services into multiple controllers if needed. I suggest that you read about services.

If you're using a REST API, take a look at ngResource. It provides some generic functionality for retrieving and storing data.

Solution 2:

Try something like:

Sharer.js:

  myApp.factory('mySharer', [function () {
    var myField = 'Initialized';

    return {
        getProperty: function() {
            return myField;
        },
        setProperty: function(value) {
            myField = value;
            return myField;
        }
    };
  }]);

Controller.js:

myApp.controller("myController", ["$scope","mySharer",        
                                      function($scope, mySharer){

        $scope.myField='HellYeah!';
        mySharer.setProperty($scope.myField);

}]);

Hope I've been helpfull.

Post a Comment for "General-purpose Gettersetter In Angularjs"