Reputation: 678
Is it posible to pass function into ng-model, for example
<input type="text" name="email" class="form-control" ng-model="createModel('email')" ng-change="addProperty(email,'email')" email required placeholder="Email">
ng-change is working fine, but ng-model="createModel(email)"
is showing this error
> Expression 'createModel('email')' is non-assignable. Element: <input
> type="text" name="email"....
In controler i have : // I just want to pass value for now
$scope.createModel = function(modelName){
console.log("Model name"+modelName);
}
I saw examples on the internet that people doing this
Upvotes: 34
Views: 72497
Reputation: 28120
Looks like AngularJS added "getter" "setter" support in version 1.3
You can scroll to the bottom of their ngModel documentation page at:
https://docs.angularjs.org/api/ng/directive/ngModel
This allows you to specify a method instead of a variable in your ngModel attribute. The method should take an optional parameter. If an argument is passed it should store that value, if no argument is passed it should return a value.
You can see an example in another Stack Overflow answer at: https://stackoverflow.com/a/28224980/984780
Upvotes: 26
Reputation: 22933
It's not possible to pass a function to ng-model
because Angular has to be able to set the value when the user changes the input value. You cannot tell Angular to instead call a function when the value is changed. What you can do is define a property on the scope with a getter and setter method, something like:
var email = '[email protected]';
Object.defineProperty($scope, 'email', {
get: function() {
return email;
},
set: function(value) {
email = value;
}
});
But I'd say that you're better of creating a $watch for the property as that will be more familiar to other Angular devs.
EDIT:
To bind to different models depending on other values, you'd still bind to the same property in ng-model
, but you can swap that out in a watch. Something like this:
var model1 = {
value: 'hi'
};
var model2 = {
value: 'hello'
};
$scope.model = model1;
$scope.checkboxValue = true;
$scope.$watch('checkboxValue', function(value) {
if (value) {
$scope.model = model1;
} else {
$scope.model = model2;
}
});
And:
<input type="text" ng-model="model.value">
<input type="checkbox" ng-model="checkboxValue">
That will change the value of your text input depending on if the checkbox is checked or not.
Upvotes: 21