Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: variable in ng-repeat without $scope is in its local scope?

here is the code:

<ul>
  <li ng-repeat="i in items" ng-class="{'red': click}">
    <span ng-click="click = !click">{{i}}</span>
  </li>
</ul>

<ul>
  <li ng-repeat="j in items" ng-class="{'red': f_click}">
    <span ng-click="fun_click($index)">{{j}}</span>
  </li>
</ul>

f_click change in fun_click function.

$scope.fun_click = (idx) ->
    $scope.f_click = !$scope.f_click

the complete codes: http://plnkr.co/edit/Zmoqbv?p=preview

I wonder that the variable click in the first list is a local variable for each ng-repeat element ?
how was it work ?

How could I make the f_click in the second list works like the click ?
Seems the $scope.f_click is the only one variable in the ng-controller.


Updated:

I think I just did things wrong.
I should not write things in "View".

read-only in View;
write-only in Controller.
http://www.jacopretorius.net/2013/07/angularjs-best-practices.html

like image 897
zx1986 Avatar asked Dec 26 '22 19:12

zx1986


1 Answers

How could I make the f_click in the second list works like the click

As I know you can't. From your 1st example click doesn't refer to any scope.

f_click refers to specific scope and any change distributes on all elements (aka on all items in your loop)

You can provide flag per value like:

$scope.items2 = [
{'name': 'Google','value':false},
{'name': 'Apple','value':false},
{'name': 'Yahoo','value':false},
{'name': 'IBM','value':false},
];

 $scope.fun_click = (item) ->
   item.value = !item.value;

HTML

 <ul>
  <li ng-repeat="j in items2" ng-class="{'red': j.value}">
    <span ng-click="fun_click(j)">{{j.name}}</span>
  </li>
</ul>

See Plunker

like image 178
Maxim Shoustin Avatar answered Dec 28 '22 07:12

Maxim Shoustin