我以'ToDo'列表的形式创建了这个plunker。我的目的是实现它的样子。
点击一个项目,它将变为“已标记”完成。然而,我发现一个奇怪的事件发生,也就是当我在点击时将'visible'变量更改为true或false时,它只影响ng-repeat中的列表项。相反,在没有ng-repeat的“ToDo”列表中,行为按预期工作(尽管不是很理想)。
为什么它以这种方式运作?
(也可以使用底部的select元素,但是当我不想要它时,通过切换'visible'的值来打破'标记完成',任何想法都会有用)
http://plnkr.co/edit/uiirZNV5yyBuB5XLst6y?p=preview
<h2>using ng-repeat:</h2>
<div ng-init="peeps = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]"></div>
<ul ng-init="visible = true">
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}" ng-repeat="peep in peeps">{{peep.name}}</li>
</ul>
<h2>NOT using ng-repeat:</h2>
<div>
<ul ng-init="visible = true">
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[0].name}}</li>
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[1].name}}</li>
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[2].name}}</li>
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[3].name}}</li>
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[4].name}}</li>
<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}">{{peeps[5].name}}</li>
</ul>
答案 0 :(得分:1)
这是因为ng-repeat
为每个项目创建了自己的范围,
您需要通过$parent
ng-repeat
还允许您访问数组中的elemnt索引,
所以你的代码看起来像
ng-repeat="(i, peep) in peeps"
...
ng-click="$parent.peeps[i].visible = !$parent.peeps[i].visible"