javascript - Angular ng-model 动态 getter 和 setter

标签 javascript angularjs angular-ngmodel

我想将 ng-model 与外部模型服务一起使用。该模型有两个方法:getValue(variable) 和 setValue(variable)。

所以在我的 html 中我希望能够做到:

<input type="text" ng-model="balance">

Note: balance is not defined on $scope in my controller. And because we are dealing with more then 4000 different variables, I don't want to define them all on $scope.

然后在更改时它必须调用模型的 setValue() 方法。所以在我的 Controller 中我想有这样的东西:

$catchAllGetter = function(variable) { // e.g. variable = 'balance'
     var value = Model.getValue(variable);
     return value;
}

$catchAllSetter = function(variable, value) { // called on change
     Model.setValue(variable, value);
}

Angular 可以实现这样的功能吗?

最佳答案

我的方法与@Dan Prince 类似,但实现方式略有不同

创建一个接受模型变量名称的指令,然后将您的模型服务注入(inject)指令本身以执行获取和设置。

Edit : As specified by @Werlang, writing an attribute that replaces ngModel will refrain you from features like validation, formatting, debounced update, ng-change etc. So instead of writing a replacement, we will instead wire up a supplementary attribute

.

    app.directive('dynamicInput', function() {
      return {
        restrict: 'A',
        link: function(scope, el, attr) {
              scope.variableName = angular.copy(attr.ngModel); // Saving the variable name

              scope[attr.ngModel] = (attr.ngModel + '_1'); // Setting a dummy value in the scope variable.
              // In your case it will look something like scope[attr.ngModel] = Model.getValue(attr.ngModel);

                scope.$watch(attr.ngModel, function(newValue, oldValue) {

                  console.log(scope.variableName + " ==> " + newValue);

                  //Model.setValue(scope.variableName, newValue);

              });

        }
      };
    })

然后在你的 HTML 中:

    <input ng-model='balance' dynamic-input />

关于javascript - Angular ng-model 动态 getter 和 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647549/

相关文章:

JavaScript 对象不改变图像

javascript - angularjs 将数组的索引传递给 ng-change 函数

javascript - 单选按钮选择验证

html - 将禁用输入字段的值设置为 ngModel

javascript - 如何使用 javascript 填写 ng-model 查询以过滤数据?

javascript - 具有多种模式的 ng-file-upload

javascript - ES6 迭代类方法

javascript - 按字母顺序对数组排序 - Angularjs

Javascript,使用一个本地对象而不是许多本地变量

AngularJS 指令 : Are Link and Compile functions meant to work together?