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?

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 Commented Feb 3, 2015 at 16:32

3 Answers 3

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];
  } 
};
Sign up to request clarification or add additional context in comments.

4 Comments

Can you give more information with this one? I have read in docs but I still don't understand :(
@Elec what don't you understand?
@Wawy What is parameter value assigned ? and Why you have to assign $scope[model] = value. Sorry it's newbie question,but I have no idea why have to do it.
When getterSetter: true is used, ngModel calls the function you define as the attribute value of ngModel in two ways, one way when it wants to read the value, as $scope.setModel(), and the other way when it wants to set the value in the model $scope.setModel(value). You are responsible for handling the getting and setting of the model in your function.
2

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

1 Comment

Thanks! Wawy's answer is good too, but I'm still using angular 1.2 (ie8 support...).
0

How about

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

and in controller

$scope.variableC = (condition) ? variableA : variableB

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.