使用ng-repeat更改无序列表中的值<ul>;还设置了一个活跃的<li>

时间:2016-03-23 18:42:07

标签: html angularjs

我一直在尝试研究如何生成列表,如果单击列表中的某个对象,它将变为活动状态。我已经设法让它在代码的非动态版本中轻松工作。但是,在AngularJS动态版上工作,我似乎无法让它工作。数据没问题,所以它不能与数据相关,它必须是我的动态代码无效。

这是一段有效的代码(但不是动态的)

                    <ul class="nav nav-pills" ng-init="catVal = 1">
                        <li ng-class="{active: catVal===1}">
                            <a href="" ng-click="catVal = 1">Category 1</a>
                        </li>
                        <li ng-class="{active: catVal===2}">
                            <a href="" ng-click="catVal = 2">Category 2</a>
                        </li>
                        <li ng-class="{active: catVal===3}">
                            <a href="" ng-click="catVal = 3">Category 3</a>
                        </li>
                    </ul>

现在我真正想要的是此代码的AngularJS动态版本。这是我迄今为止尝试过的失败。

                    <ul class="nav nav-pills">
                        <li ng-repeat="category in model" ng-init="catVal = 1" ng-class="active: catVal === category.catID ">
                            <a href="" ng-click="catVal = category.catID">{{category.catName}}</a>
                        </li>
                    </ul>

catID与类别相关联,并且应该提供与上一个列表相同的结果。我把名字放在正确的地方,只是价值不起作用。

1 个答案:

答案 0 :(得分:2)

试试这个。

&#13;
&#13;
var app = angular.module("app",[]);

app.controller("ctrl" , function($scope){
  $scope.rowIndex = -1;
  $scope.items = [{"name":"ali","score":2},{"name":"reza","score":4},{"name":"amir","score":5},{"name":"asd","score":10}];
 
  $scope.selectRow = function(index){
      if(index == $scope.rowIndex)
        $scope.rowIndex = -1;
        else
          $scope.rowIndex = index;
    }
  });
&#13;
.active{
  background-color:#a11af0;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">

    <ul class="nav nav-pills" ng-init="catVal = 1">
       <li ng-repeat="item in items" ng-class="{'active':rowIndex == $index }" ng-click="selectRow($index)">
           <a href="">{{item.name}}</a>
        </li>
                       
     </ul>        
</div>
&#13;
&#13;
&#13;