tommyd456
tommyd456

Reputation: 10683

ng-model - getting name and value of input box

I have an update function and a number of input boxes. Each input has an ng-blur attached to it so that the update function is called whenever the cursor leaves the box.

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

The input for name look like this:

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

As I need to be able to post a JSON object in the form {"name" : "bob smith"} what's a good way of generating the "key" of the object bearing in mind that it will differ depending on the input box that's being used at the time?

Upvotes: 0

Views: 1492

Answers (2)

kuzyn
kuzyn

Reputation: 1995

EDIT ↓

I have made this jsfiddle to illustrate a way to do it more cleanly & that would scale more easily: http://jsfiddle.net/kuzyn/k5bh0fq4/5/

EDIT ↑

Why not simply pass a second string argument? It's not a fancy way to do it but it would work:

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

And

$scope.update = function(data, key) {
    console.log(key, data);
}

Upvotes: 2

jusopi
jusopi

Reputation: 6813

It might be a little more work but it is much more scalable. You could make use of the ng-form and naming your form inputs. By naming your form and inputs, you are creating a form reference on your scope via $scope[form-name]. Each named input within that form then sets an input reference via $scope[form-name][input-name].

I'm coding this in coffeescript (to preserve my sanity, sorry)

form

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

update & save func

# 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

Upvotes: 0

Related Questions