AngularJS > Repeaters

Add item to collection in AngularJS

How to add an item to collection in AngularJS?


In the pervious post, we learnt how to list data from JSON collection. In this post, we shall learn how to add record into that collection.

To add an item to collection, we can create a function in the controller that will be responsible to add item. The item can be added to the colleciton using .splice function of JavaScript.

Below code snippet is almost same as the previous post except the highlighted code snippets.

<script>
    var members = [
            { username: 'SheoNarayan', address: 'Hyderabad' },
            { username: 'Munna', address: 'Bokaro' },
            { username: 'Jay', address: 'Aurangabad' },
            { username: 'Sreeni', address: 'New York' }
    ];

    var app = angular.module("app", []);
    app.controller("MemberController", ["$scope", function ($scope) {
        $scope.Members = members;

        $scope.AddMember = function () {
            $scope.Members.splice(2, 0, { username: 'Bill', address: 'Washington DC' });
        };

    }]);

</script>

<div ng-app="app">
    <h4>Listing item from the collection</h4>
    <div ng-controller="MemberController">
        <ul>
            <li ng-repeat="member in Members">
                {{$index + 1}}.  Name: {{member.username }} | Address: {{ member.address}}
            </li>
        </ul>
        <button ng-click="AddMember()">Add a member</button>
    </div>
</div>

Notice that in the controller we have added a method (also called behavior) named "AddMember". In this method, we have used .splice function of JavaScript to add a record.

.splice() JavaScript function

.splice() function of JavaScript has three parameter.

  1. 1st parameter - at what position of the array the items will be added or remoeved.
  2. 2nd parameter - how many items will be removed, if 0 no item will be removed.
  3. 3rd parameter (optional) - item to be added

In above case, we have added a record (3rd parameter), to the second position (1st parameter) of Members property (the members array) of the $scope. In this case, 2nd parameter value is 0 so no item will be removed from array.

This AddMember() method is being called from "Add a member" button. Notice the ng-click directive in the button.

Output

Add item to collection in AngularJS

 Views: 17175 | Post Order: 24




Write for us






Hosting Recommendations