user3871
user3871

Reputation: 12718

Angular prepend to top with ng-repeat off by one

I am trying to add an object to the top of my list, rather than bottom, with ng-repeat. I thought the way to do this would be unshift or splice with index 0, but one pesky object remains at the top.

Datastructure:

$scope.categories = [
    {...}, {...}, {...}
]

Add object function:

$scope.addObj = function () {
    $scope.categories.unshift({
        category : ''
    });
};

How it appears in the HTML list:

Click add obj: How it appears in the HTML list AFTER prepending:

I console.log'ed my $scope.categories array and verified that the new object had been added at array index 0. What is going on here?

I initially tried splice with the same result:

$scope.addObj = function () {
    $scope.categories.splice(0, 0, {
        category : ''
    });
};

HTML:

<tr ng-repeat="c in categories | orderBy:sortType:sortReverse | filter:searchQuestions track by $index">
    <td>
        <div class="form-group" ng-class="{ 'has-error' : categoryForm.username.$invalid && !categoryForm.email.$pristine }">
            <input type="text" name="category" placeholder="New Category" class="form-control" ng-model="c.category" required>
        </div>
    </td>

Upvotes: 1

Views: 261

Answers (2)

zeeshan Qurban
zeeshan Qurban

Reputation: 387

You should change your code to this.

$scope.addObj = function () {
 var c = $scope.categories.length + 1;
 var category = new String('category' + c)
$scope.categories.splice(0, 0, category);};

Upvotes: 0

Muthukannan Kanniappan
Muthukannan Kanniappan

Reputation: 2079

Add the input form before ng-repeat

<tr>
    <td>
        <div class="form-group" ng-class="{ 'has-error' : categoryForm.username.$invalid && !categoryForm.email.$pristine }">
            <input type="text" name="category" placeholder="New Category" class="form-control" ng-model="c.category" required>
        </div>
    </td>
</tr>

<tr ng-repeat="c in categories | orderBy:sortType:sortReverse | filter:searchQuestions track by $index">
   <td>
      {{c.category}}
   </td>
</tr>

This is a sample try modifying your code based on this.

categories.unshift will not guarantee to display the new item in first index because you have applied orderBy filter.

Upvotes: 1

Related Questions