Pranav
Pranav

Reputation: 972

Create JSON object from multiple row input fields using Angular JS

The multiple row input fields are

enter image description here

Using jQuery I created a method to derive JSON

function createReminderJSON() {
         jsonObj = [];
        $("input[class=occasion]").each(function() {

            var occasion = $(this).val();

            if ('' !== occasion) {
                var fname = $('.fname').val();
                var lname = $('.lname').val();

                item = {}
                item["occasion"] = occasion;
                item["firstName"] = fname;
                item["lastName"] = lname;

                jsonObj.push(item);
            }

        });
        console.log(jsonObj);
        $.ajax({
            type : "post",
            contentType : "application/json",
            url : "/add/reminder",
            data : JSON.stringify(jsonObj)
        }); 
    }

JSON created is

[{occasion:1,firstName:Tim,lastName:Cook},{occasion:1,firstName:Steve,lastName:Jobs}]

HTML of input fields:

<tr>
    <td><input type="text" name="occasion" placeholder="occasion" class="occasion" ng-model="rem.occasion"/></td>
    <td><input type="text" name="firstName" placeholder="fname" class="fname" ng-model="rem.firstName"/><td>
    <td><input type="text" name="lastName" placeholder="lname" class="lname" ng-model="rem.lastName"/><td>
</tr>

Angular JS method invoked on ng-click=addReminder() is

function Reminder($scope,$http){
        $scope.addReminder = function() {
            var reminders = $scope.rem;
            alert(reminders);
            $http.post('/add/reminder', reminders).success(function(data) {
                alert("Success!");
            });
        }
    }

Is angular.forEach necessary? How can I create JSON using Angular JS silmilar to the jQuery one. The alert is giving me undefined when I tried with a single row input.

Upvotes: 1

Views: 1660

Answers (2)

dev_khan
dev_khan

Reputation: 717

You just need to declare an empty object in the controller.

$scope.rem = {};

Upvotes: 1

Jochen van Wylick
Jochen van Wylick

Reputation: 5401

No, it's not. Remember that JSON stands for Javascript Object Notation. It is the way an object is being described. So the models in your AngularJS controller - as soon as they are serialized 'over the wire' by a POST for example, look like the JSON you want.

Here's a Fiddle that demonstrates: http://jsfiddle.net/358uqccy/3/. The | json filter converts an object into JSON to show you that the JSON of your model is available at all times.

Upvotes: 0

Related Questions