Ng-click doesn't change value in HTML when in ng-repeat

So I don't know if this is a problem for AngularJS or my understanding.

In my application I have ng-repeat

and I need to track an active $index

one that can be changed when another element is clicked. So I thought I would do something like:

<body ng-init="active = -1">
    <span ng-repeat="item in items" ng-bind="item" ng-click="active = $index"></span>
</body>

      

But that doesn't work; I know if I change ng-click

to ng-click="select($index)

and apply the change in my controller it works. But I would like to know why the implementation above is not working.

Interestingly, if you don't ng-repeat

, this DOES work, i.e.

<body ng-init="active = -1">
    <span ng-click="active = 0">Item 1</span>
    <span ng-click="active = 1">Item 2</span>
    ...
</body>

      

Here is the Plunker of the two scenarios. Why?

+3


source to share


1 answer


You can fix it like below,

in HTML

<span ng-repeat="item in items track by $index" ng-click="x.badClick = $index"> // x.badClick

      

on the controller

$scope.x = {};

      

thats because it creates a new area for each repeat, link ,



link,

Each template instance gets its own scope, where the given loop variable is set to the current

if u like to x.badClick

, x

not in the field of ng-repeat, so it will check x

in the next upper field if you need more, check prototypical inheritance

here is a good demonstration of the link


you can reference parent properties using also $parent

, so this will work as well,

<span ng-repeat="item in items track by $index" ng-click="$parent.badClick = $index">

      

+3


source







All Articles