简体   繁体   中英

General-purpose getterSetter in AngularJS

Documentation for ngModel has an example for getterSetter:

angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  var _name = 'Brian';
  $scope.user = {
    name: function(newName) {
     // Note that newName can be undefined for two reasons:
     // 1. Because it is called as a getter and thus called with no arguments
     // 2. Because the property should actually be set to undefined. This happens e.g. if the
     //    input is invalid
     return arguments.length ? (_name = newName) : _name;
    }
  };
}]);

This is exactly what I would need, but I wouldn't like to write this part over and over again in different contexts. Is it possible to create a generic getterSetter? Like

$scope.user.name = nameGetterSetter;

I just can't see how that global function could get or set any specific instance without passing scope.

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() {

    function User(name) {
        this.name = name;
    }

    return User;

});

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM