Unknown developer
Unknown developer

Reputation: 5940

$index does not diminish its value when ng-if removes an element

My HTML:

<section  ng-repeat="Rule in Data track by $index" ng-if="!Rule.is_deleted">
    {{$index}}
    {{ Rule.title }}<a ng-click="removeElem($index)"></a> 
</section>

and the controller:

$scope.removeElem = function (elemIndex) {
     $scope.Data[elemIndex].is_deleted = true;              
}

$scope.addElem = function(obj) {
    $scope.Data.push(obj);
}

There is a functionality of adding/removing objects to/from $scope.Dataarray. Let's say there are two items in $scope.Data; I am removing one and add a new one. Therefore, the items are still two. The problem is that $index associates the newly created second item with value 2 and not value 1 as I expected (ng-if removes the item from the DOM, isn't it?). Why that? How may I oblige $index to diminish its value if removing an item?

Upvotes: 1

Views: 105

Answers (3)

jbrown
jbrown

Reputation: 3025

Don't use $index for this, just pass the object to the function. Also, this is a better use case for a filter rather than using ng-if to hide/show a row

HTML

<section ng-repeat="Rule in Data | filter: {is_deleted: false}">
  {{ Rule.title }}
  <a ng-click="removeElem(Rule)">Remove</a>
</section>

Controller

$scope.removeElem = function(rule) {
  rule.is_deleted = true;
};

Upvotes: 1

Sumit Deshpande
Sumit Deshpande

Reputation: 2155

Using $index should be avoided.Instead of using $index, prefer to pass the actual objects around. E.g. ng-click="removeElem(Rule)"

Upvotes: 0

TheSharpieOne
TheSharpieOne

Reputation: 25726

You probably want to filter rather than using ng-if in the ng-repeat.

<section ng-repeat="Rule in (Data | filter: {is_deleted: false}) track by $index">
    {{$index}}
    {{ Rule.title }}<a ng-click="removeElem($index)"></a> 
</section>

fiddle showing the difference: https://jsfiddle.net/u6nqrq5o/

Upvotes: 1

Related Questions