AngularJs中li的索引

时间:2014-07-15 13:39:04

标签: angularjs

使用AngularJs&自举。

尝试获取每个li项目的索引,以便我可以将每个项目的颜色设置为不同。 我怎样才能做到这一点。试过这样的事情。

HTML:

<ul>
   <li class="alert alert-{{bgcolor($index)}}" ng-repeat="item in todolist">     
    <span>{{item.name}}</span>    
   </li>                                                        
</ul>

JS:

$scope.todolist = [
                { name: "Buy Food", done: false },
                { name: "Eat Food", done: false },
                { name: "Cook Food", done: true }
            ];
$scope.bgcolor = function (i) {
                var color = "";
                switch(i)
                {
                    case 1: color="success";
                    case 2: color = "warning";
                    case 3: color = "danger";
                }
                return color;

            };

3 个答案:

答案 0 :(得分:4)

这应该可行,但您在交换机中遗漏了break;

switch(i) {
    case 1: color="success"; break;
    case 2: color = "warning"; break;
    case 3: color = "danger"; break;
}

$index也是0,所以第一项不会从中获得一个类。

答案 1 :(得分:2)

you can try something like this
<ul>
   <li class="alert alert-{{bgcolor($index)}}" ng-repeat="item in todolist">     
    <span>{{item.name}}</span>    
   </li>                                                        
</ul>

JS:

    $scope.todolist = [
                    { name: "Buy Food", done: false },
                    { name: "Eat Food", done: false },
                    { name: "Cook Food", done: true }
                ];
    $scope.bgcolor = function (i) {
                    var color = ['success','warning','danger'];

                    return color[index];

                };

答案 2 :(得分:0)

将$ index与ng-repeat一起使用。 (重复元素的迭代器偏移量(0..length-1) https://docs.angularjs.org/api/ng/directive/ngRepeat