3

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

In my app, I have an ng-repeat and I need to keep track of the active $index, which can be changed when you click on another item. 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 this does not work; I know if I change the ng-click to ng-click="select($index) and apply the change in my controller, this would work. But I'd like to know why the implementation above doesn't work.

Interestingly, if you don't have an 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 a Plunker of these two scenarios. Why?

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • So the solution seems to be "ng-click="$parent.badClick = $index"" – Marvin Smit Nov 01 '14 at 09:52
  • @MarvinSmit, yeah I was reading the page. Actually, I like the solution by Kalhano better since it doesn't rely on $parent and the problems mentioned there. – Kousha Nov 01 '14 at 09:53
  • another possible one http://stackoverflow.com/questions/17039926/adding-parameter-to-ng-click-function-inside-ng-repeat-seems-not-to-work – Ekin Nov 01 '14 at 09:54
  • @E.H.B, thanks. But i really like the answer below, since I am only updating active index and I rather keep it within the HTML page itself – Kousha Nov 01 '14 at 09:56
  • @Kousha yes, that's a really good one – Ekin Nov 01 '14 at 09:59

1 Answers1

3

You can fix that like below,

in HTML

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

on controller

$scope.x = {};

thats because its create new scope for each repeat, reference ,,

reference said ,

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

if u do like x.badClick , x is not in the ng-repeat scopes, so it will check the x in next top scope, if u need more, check about prototypical inheritance here is a good demonstration , link


you can refer the parent properties by using $parent also, so this will also work,

<span ng-repeat="item in items track by $index" ng-click="$parent.badClick = $index">
Community
  • 1
  • 1
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92