Search code examples
javascriptangularjsangularjs-scope

Get all input fields onblur


I made the following code (jsFiddle) to get the input of a text field:

var app = angular.module('myApp', [
    'my.controllers'
]);

var controllers = angular.module('my.controllers', []);
controllers.controller('MyController', function($scope) {

});

controllers.controller('listdata', function($scope, $http) {

    $scope.editItem = function(event) {
        var fieldTitle = $(event.currentTarget).attr("data-id");
        var fieldValue = event.target.value;
        console.log(fieldTitle + " : " + fieldValue);
    };
})

In this case the function only returns the field name and field value of which the text is changed. What is the correct way to get all values of all input fields, when one of the fields is changed?


Solution

  • Regarding to your question

    "What is the correct way to get all values of all input fields, when one of the fields is changed?", this fiddle shows you one of the correct ways to get all the results on field change.

    The basic idea is to use ng-model directive for input fields: in fact, your code

    var fieldTitle = $(event.currentTarget).attr("data-id");
    var fieldValue = event.target.value;
    

    It's a sign you are not thinking in a angular way (and i suggest you to read this excellent answer to get an idea of what you should do).

    The solution

    Use ng-model to bind your variables to your scope, and ng-change to intercept changes in them:

    <input type="text" ng-model="id" ng-change="editItem(id)">
    <input type="text" ng-model="title" ng-change="editItem(title)">
    <input type="text" ng-model="number" ng-change="editItem(number)">
    

    and in your controller:

    $scope.editItem = function (value) {
        console.log("currentValue" + value);
        console.log("ID:" + $scope.id + " Title: " + $scope.title +" Number:" + $scope.number);
    };