最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ng-model in input based on another variable - Stack Overflow

programmeradmin7浏览0评论

I han an input filed in my angular app <input type="text" ng-model="variableA">. I want to use variableA or variableB basing on some condition. I've tried something like this ng-model="condition ? variableA : variableB" but it throws Error: [ngModel:nonassign]. Any ideas how to make it work?

I han an input filed in my angular app <input type="text" ng-model="variableA">. I want to use variableA or variableB basing on some condition. I've tried something like this ng-model="condition ? variableA : variableB" but it throws Error: [ngModel:nonassign]. Any ideas how to make it work?

Share Improve this question asked Feb 3, 2015 at 16:27 BodzioBodzio 2,5202 gold badges21 silver badges37 bronze badges 1
  • 1 you can define a variableC for your 'root model' and assigns it conditionally to variableA or variableB at the beginning of your angular controller – Gentle_B Commented Feb 3, 2015 at 16:32
Add a ment  | 

3 Answers 3

Reset to default 5

You could make use of ngModelOptions:

<input type="text" ng-model="setModel" ng-model-options="{getterSetter: true}">

In your controller:

$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];
  } 
};

ngModel has to be a property expression (following the fules of $parse).

Try using a proxy then watch that variable to then assign to A or B:

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

In your controller:

$scope.$watch('variableC', function(value) {

  if(someCondition) {
    $scope.variableA = value;
  } else { 
    $scope.variableB = value;
  }
});

How about

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

and in controller

$scope.variableC = (condition) ? variableA : variableB
发布评论

评论列表(0)

  1. 暂无评论