<li ng-click="visible = !visible" ng-class="{'strike': !visible, 'none': visible}" ng-repeat="peep in peeps">{{peep.name}}</li>
上面的代码允许我点击每个重复的li
并有条件地将类.strike
设置为每个。
我正在处理的是这些列表项的'大规模'切换,这也允许我将.strike
类应用于所有列表项,除了通过{选择的那个{1}}元素。
我确信这是一个范围问题,但由于某种原因我无法实现这一目标。我错过了什么?
答案 0 :(得分:3)
每次ng-repeat
次迭代都会创建一个新的scope
,因此visible
属性会锁定在当前重复范围内。选项上的ng-repeat
也为每次迭代创建一个新的scope
,但visible
属性不与之前的ng-repeat
范围共享,它们是完全不同的范围。
对于Davin Tryon给出的解决方案,这是一种不同的方法。
答案 1 :(得分:2)
要使其工作,您需要使visible
成为数据项的属性。然后,您可以切换其状态,而不仅仅是松散范围的值。
<body>
<h3>using ng-repeat:</h3>
<p>(click a name to cross it out)</p>
<div ng-init="peeps = [
{name:'John', age:25, gender:'boy', visible:true},
{name:'Jessie', age:30, gender:'girl', visible:true},
{name:'Johanna', age:28, gender:'girl', visible:true},
{name:'Joy', age:15, gender:'girl', visible:true},
{name:'Mary', age:28, gender:'girl', visible:true},
{name:'Peter', age:95, gender:'boy', visible:true},
{name:'Sebastian', age:50, gender:'boy', visible:true},
{name:'Erika', age:27, gender:'girl', visible:true},
{name:'Patrick', age:40, gender:'boy', visible:true},
{name:'Samantha', age:60, gender:'girl', visible:true}
]"></div>
<ul ng-init="visible = true">
<li ng-click="peep.visible = !peep.visible" ng-class="{'strike': !peep.visible, 'none': peep.visible}" ng-repeat="peep in peeps">{{peep.name}}</li>
</ul>
<div>
<span>select only:</span>
<select ng-model="selectedPeep" ng-change="peeps[selectedPeep].visible = !peeps[selectedPeep].visible">
<option ng-repeat="peep in peeps" ng-value="$index">{{peep.name}}</option>
</select>
<span>{{changed.name}}</span>
</div>
</body>