在ng-model中传递函数

Mar*_*ltz 34 javascript angularjs

例如,将函数传递给ng-model是否可行

<input type="text" name="email" class="form-control" ng-model="createModel('email')" ng-change="addProperty(email,'email')" email required placeholder="Email">
Run Code Online (Sandbox Code Playgroud)

ng-change工作正常,但ng-model="createModel(email)"显示此错误

> Expression 'createModel('email')' is non-assignable. Element: <input
> type="text" name="email"....
Run Code Online (Sandbox Code Playgroud)

在控制器中我有://我只想暂时传递价值

  $scope.createModel = function(modelName){
     console.log("Model name"+modelName);
  }
Run Code Online (Sandbox Code Playgroud)

我在互联网上看到人们这样做的例子

Lui*_*rez 25

看起来AngularJS在版本1.3中添加了"getter""setter"支持

您可以滚动到他们的ngModel文档页面的底部:

https://docs.angularjs.org/api/ng/directive/ngModel

这允许您在ngModel属性中指定方法而不是变量.该方法应该采用可选参数.如果传递了一个参数,它应该存储该值,如果没有传递参数,它应该返回一个值.

您可以在另一个Stack Overflow答案中看到一个示例:https://stackoverflow.com/a/28224980/984780


And*_*ahl 20

无法传递函数,ng-model因为Angular必须能够在用户更改输入值时设置该值.当值改变时,您无法告诉Angular调用函数.你可以做的是使用getter和setter方法在作用域上定义一个属性,如:

var email = 'test@test.com';
Object.defineProperty($scope, 'email', {
  get: function() {
    return email;
  },
  set: function(value) {
    email = value;
  }
});
Run Code Online (Sandbox Code Playgroud)

但是我会说你最好为这个房产创造一个$ watch,因为其他Angular开发者会更熟悉.

编辑:要根据其他值绑定到不同的模型,您仍然绑定到相同的属性ng-model,但您可以在手表中交换它.像这样的东西:

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

和:

<input type="text" ng-model="model.value">
<input type="checkbox" ng-model="checkboxValue">
Run Code Online (Sandbox Code Playgroud)

这将改变文本输入的值,具体取决于是否选中了复选框.