Angular js ng-class false在ng-repeat中不起作用

时间:2014-08-18 10:08:15

标签: javascript html5 angularjs angularjs-ng-repeat ng-class

如果选择li,我想突出显示radio。 在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>

2 个答案:

答案 0 :(得分:4)

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

有关详细信息,请阅读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>

在您的控制器中,事先初始化model

$scope.model = {
  radioBox: undefined
};

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

答案 1 :(得分:1)

  

如果表达式求值为一个对象,则对于具有truthy值的对象的每个键值对,相应的键将用作类名。

ng-class="{'highlight':radioBox==friend.name}"