2

The following code doesn't work -

<div ng-init="selected=-1">
<ul ng-repeat="x in arr">
    <li ng-click="selected = $index">...</li>
</ul>

When I click on one of the lis, the variable selected remains as -1. But the following does work -

<div ng-init="selected=-1">
<ul ng-repeat="x in arr">
    <li ng-click="setTo($index)">...</li>
</ul>

$scope.setTo = function(index){selected = index;}

Why is that? Nothing functional seems to have changed.

4
  • Here is an explanation to your problem.stackoverflow.com/questions/26290982/… Answer talks about ng-if here it is ng-repeat both creates child scopes. I wouldn't suggest using $parent though.. Commented Oct 13, 2014 at 19:45
  • One more thing, try not to use ng-init for initializing a variable outside ng-repeat. it should actually be done in the controller. If you look at official documentation it states The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope. Commented Oct 13, 2014 at 20:16
  • @PSL it was just for the purposes of this example. Commented Oct 13, 2014 at 20:17
  • Alright cool.. Just wanted to let you know based on the code posted... ;) Commented Oct 13, 2014 at 20:17

2 Answers 2

3

ng-repeat directive creates it's own scope for each item in arr, so when expression selected = $index is executed, the new property selected is created on that scope, at the same time parent scope remains untouched.

Is why your selected property does not change in the first case.

Sign up to request clarification or add additional context in comments.

2 Comments

Are you saying that if I do $parent.selected = $index it would work?
Yes, it should help you
3

Since the ngRepeat directive creates its own scope, you need to refer to $parent.selected in the first example:

<li ng-click="$parent.selected = $index">

http://plnkr.co/edit/9iUgp57KwvrlC3TDO3YC?p=preview

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.