Reputation: 2520
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?
Upvotes: 0
Views: 4347
Reputation: 6269
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];
}
};
Upvotes: 5
Reputation: 21005
How about
<input type="text" ng-model="variableC">
and in controller
$scope.variableC = (condition) ? variableA : variableB
Upvotes: 0
Reputation: 25421
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;
}
});
Upvotes: 2