To avoid this problem, you can use "track by" with ng-repeat. In track by you have to use angular expression that will be used to uniquely identify the each items in collection or model. "track by" tells the angular js that how angular js will track the association between DOM and the model (i.e. collection).
Example# ng-repeat is a built in directive in Angular which lets you iterate an array or an object and gives you the ability to repeat an element once for each item in the collection. To repeat multiple DOM elements by defining a start and an end point you can use the ng-repeat-start and ng-repeat-end directives.
Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
See plunker
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
See plunker
As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker
JS:
$scope.setSelected = function(selected) {
$scope.selected = selected;
}
HTML:
{{ selected }}
<ul>
<li ng-class="{current: selected == 100}">
<a href ng:click="setSelected(100)">ABC</a>
</li>
<li ng-class="{current: selected == 101}">
<a href ng:click="setSelected(101)">DEF</a>
</li>
<li ng-class="{current: selected == $index }"
ng-repeat="x in [4,5,6,7]">
<a href ng:click="setSelected($index)">A{{$index}}</a>
</li>
</ul>
<div
ng:show="selected == 100">
100
</div>
<div
ng:show="selected == 101">
101
</div>
<div ng-repeat="x in [4,5,6,7]"
ng:show="selected == $index">
{{ $index }}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With