ng-model - 获取输入框的名称和值

时间:2015-12-11 16:30:23

标签: angularjs

我有更新功能和许多输入框。每个输入都附加一个ng-blur,以便在光标离开框时调用更新函数。

$scope.update = function(data) {
    console.log(data); //outputs value in the textbox
    //how can I output/access the key?
}

name的输入如下所示:

<input type="text" ng-model="user.name" ng-blur="update(user.name)"/>

因为我需要能够以{"name" : "bob smith"}形式发布JSON对象,所以生成对象“键”的好方法是记住它会因使用的输入框而有所不同当时?

2 个答案:

答案 0 :(得分:2)

编辑↓

我已经制作了这个jsfiddle来说明一种更干净利落的方式。这将更容易扩展:http://jsfiddle.net/kuzyn/k5bh0fq4/5/

编辑↑

为什么不简单地传递第二个字符串参数?这不是一种花哨的方式,但它会起作用:

diff --git a/Gemfile.lock b/Gemfile.lock
index b85dabe..a909ee0 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -57,6 +57,7 @@ GEM
     code_metrics (0.1.3)
     coderay (1.1.0)
     colored (1.2)
+    colorize (0.7.7)
     concord (0.1.5)
       adamantium (~> 0.2.0)
       equalizer (~> 0.0.9)
@@ -215,7 +216,8 @@ GEM
     slop (3.6.0)
     spoon (0.0.4)
       ffi
-    sshkit (1.8.1)
+    sshkit (1.7.1)
+      colorize (>= 0.7.0)
       net-scp (>= 1.1.2)
       net-ssh (>= 2.8.0)
     terminal-table (1.5.2)

<input type="text" ng-model="user.name" ng-blur="update(user.name, 'name')"/>

答案 1 :(得分:0)

它可能需要更多工作,但它的可扩展性更高。您可以使用ng-form并命名表单输入。通过命名表单和输入,您将通过$scope[form-name]在范围上创建表单参考。然后,该表单中的每个命名输入都通过$scope[form-name][input-name]设置输入引用。

我在coffeescript中对此进行编码(为了保持理智,对不起)

<强>形式

<form name="myForm">
    <input name="name" ng-model="user.name" ng-blur="update(user)"/>
    <input name="email" ng-model="user.email" ng-blur="update(user)"/>
    <input name="other" ng-model="user.other" ng-blur="update(user)"/>
</form>

更新&amp;保存功能

# key is what changed in case you need to do something special on the put call to server
$scope.save = (data, key)->

# pseudo-code
$scope.update = (data)->
    for name, input of $scope.myForm
       if input?.$dirty
           $scope.save data, name
           break
相关问题