Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
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.. –  PSL Oct 13 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. –  PSL Oct 13 at 20:16
    
@PSL it was just for the purposes of this example. –  David Grinberg Oct 13 at 20:17
    
Alright cool.. Just wanted to let you know based on the code posted... ;) –  PSL Oct 13 at 20:17

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Are you saying that if I do $parent.selected = $index it would work? –  David Grinberg Oct 13 at 18:44
    
Yes, it should help you –  Alexei Oct 13 at 18:45

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.