通过功能NG-模型 [英] Pass function in ng-model

查看:127
本文介绍了通过功能NG-模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是更多钞票传递函数为NG-模式,例如:

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-变化工作正常,但 NG-模式=createModel(电子邮件)正显示出此错误

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

在CONTROLER我有:
//我只是想现在通过值

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

推荐答案

这是不可能传递给 NG-model的功能,因为角必须能够设置当用户改变输入值值。你不能告诉角当值改变,而不是调用一个函数。你可以做的是一个getter和setter方法​​的范围定义属性,是这样的:

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.

编辑:
绑定到依赖于其他值不同的车型,你还是会绑定到 NG-模型相同的属性,但你可以换说出来的手表。事情是这样的:

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;
  }
});

<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.

这篇关于通过功能NG-模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆