0

I am using ng-repeat to create an array of items (a list), I would like to have an id against each item to be it's position in the array.

JS FIDDLE DEMO HERE: http://jsfiddle.net/m62Ez/15/

Please have a look at the following, looks like the ng-model="item.id" is never assign. Any suggestions much appreciated.

HTML

 <div ng-controller="MainCtrl">
    <button ng-click="addItem()">Add Item</button>

    <ul>
        <li ng-repeat="item in items">
            <input type="hidden" ng-model="item.id" ng-value="{{$index}}" />
            <input type="text" ng-model="item.name" />
        </li>
    </ul>
    <hr />
    <button ng-click="saveAll()">Save All</button>
</div>

JS

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

    $scope.items = [];
    $scope.addItem = function () {
        $scope.items.push({});
    }
    $scope.saveAll = function () {
        console.log($scope.items); // item's do not have id's
    }

});

1 Answer 1

2

The hidden field isn't useful. If you want your objects to have an ID, then generate them with an ID:

$scope.addItem = function () {
    $scope.items.push({id: $scope.items.length});
}

Updated jsfiddle: http://jsfiddle.net/K7DgE/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.