简体   繁体   English

AngularJS中的通用getterSetter

[英]General-purpose getterSetter in AngularJS

Documentation for ngModel has an example for getterSetter: ngModel的文档有一个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? 是否可以创建一个通用的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. 在我看来,你实际上并不需要使用getterSetter。 Creating a separate model for handling users would be more useful. 为处理用户创建单独的模型会更有用。 One way to do this is to create an Angular service. 一种方法是创建一个Angular服务。 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 . 如果您使用的是REST API,请查看ngResource It provides some generic functionality for retrieving and storing data. 它提供了一些检索和存储数据的通用功能。

Try something like: 尝试类似的东西:

Sharer.js: Sharer.js:

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

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

Controller.js: Controller.js:

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

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

}]);

Hope I've been helpfull. 希望我一直很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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