简体   繁体   中英

Pass function in ng-model

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

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

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 = 'test@test.com';
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM