gpt4 book ai didi

javascript - Angular js ng-class错误条件在ng-repeat中不起作用

转载 作者:行者123 更新时间:2023-11-30 08:42:11 27 4
gpt4 key购买 nike

如果选择了 radio,我想突出显示 li。在 ng-repeat 中,ng-class true 条件有效,但 false 条件无效,请检查下面的代码

<div ng-init="friends = [
{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'}
]">
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends" ng-class="{true:'hightlight',false:''}[radioBox==friend.name]">
<input type="radio" name="friends" ng-model="radioBox" value="{{friend.name}}" />
</li>
</ul>
</div>

最佳答案

这是因为 ng-repeat 为每个 li 元素创建了一个新的子作用域,因此每个 li 元素都有自己的 radioBox 值在它自己的范围内。

有关更多详细信息,请阅读 Understanding-Scopes .

你可以通过在你的 ng-model 中加入 . 来避免这个问题,例如使用 model.radioBox 像这样:

<li class="animate-repeat" ng-repeat="friend in friends" ng-class="{true:'hightlight',false:''}[model.radioBox==friend.name]">
<input type="radio" name="friends" ng-model="model.radioBox" value="{{friend.name}}" />
</li>

然后在您的 Controller 中,预先初始化模型:

$scope.model = {
radioBox: undefined
};

示例 Plunker: http://plnkr.co/edit/TcOrxhSzYtN2KCxF2M3g?p=preview

关于javascript - Angular js ng-class错误条件在ng-repeat中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com