角度ng模型动态getter和setter

Jan*_*ans 5 javascript angularjs angular-ngmodel

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

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

<input type="text" ng-model="balance">
Run Code Online (Sandbox Code Playgroud)

注意:我的控制器中的$ scope上没有定义balance.而且因为我们处理的是4000多个不同的变量,所以我不想在$ scope上定义它们.

然后在更改时,它必须调用模型的setValue()方法.所以在我的控制器中我希望有类似的东西:

$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);
}
Run Code Online (Sandbox Code Playgroud)

Angular可以这样吗?

Man*_*kla 3

我的方法类似于@Dan Prince,但实现有点不同

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

编辑:正如 @Werlang 所指定的,编写一个替换 ngModel 的属性将避免您使用验证、格式化、去抖更新、ng-change 等功能。因此,我们不会编写替换项,而是连接一个补充属性

    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);

              });

        }
      };
    })
Run Code Online (Sandbox Code Playgroud)

然后在你的 HTML 中:

    <input ng-model='balance' dynamic-input />
Run Code Online (Sandbox Code Playgroud)

  • 这样你就可以释放 ng-model 内置的所有功能,例如验证、格式化、去抖更新、ng-change 等 (3认同)