繁体   English   中英

ng-model 中的传递函数

[英]Pass function in ng-model

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

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

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

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

在控制器中我有://我现在只想传递值

  $scope.createModel = function(modelName){
     console.log("Model name"+modelName);
  }

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

看起来 AngularJS 在 1.3 版中添加了“getter”“setter”支持

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

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

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

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

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

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

但我会说你最好为属性创建一个 $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;
  }
});

和:

<input type="text" ng-model="model.value">
<input type="checkbox" ng-model="checkboxValue">

这将根据是否选中复选框来更改文本输入的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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