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?
-
1you can define a variableC for your 'root model' and assigns it conditionally to variableA or variableB at the beginning of your angular controllerGentle_B– Gentle_B2015-02-03 16:32:21 +00:00Commented Feb 3, 2015 at 16:32
Add a comment
|
3 Answers
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];
}
};
4 Comments
Elec
Can you give more information with this one? I have read in docs but I still don't understand :(
Wawy
@Elec what don't you understand?
Elec
@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.Wawy
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.
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
Bodzio
Thanks! Wawy's answer is good too, but I'm still using angular 1.2 (ie8 support...).