基于另一个变量的输入中的ng-model

Bod*_*zio 0 javascript angularjs

我在我的角度应用程序中输入了一个输入<input type="text" ng-model="variableA">.我想使用variableAvariableB基于某些条件.我尝试过类似的东西,ng-model="condition ? variableA : variableB"但它会抛出Error: [ngModel:nonassign].任何想法如何使其工作?

Waw*_*awy 5

您可以使用ngModelOptions:

<input type="text" ng-model="setModel" ng-model-options="{getterSetter: true}">
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

$scope.setModel = function(value) {
  var model = '';
  if (condition) {
    model = "variableA";
  } else {
    model = "variableB";
  }

  if (angular.isDefined(value)) {
    return ($scope[model] = value);
  } else {
    return $scope[model];
  } 
};
Run Code Online (Sandbox Code Playgroud)