使用angularjs选择多个列表项 [英] Select multiple list items using angularjs

查看:74
本文介绍了使用angularjs选择多个列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从无序列表中的元素中选择一个特定的列表项.它应该显示为选中状态,我需要通过更改一些背景来显示它.

I'm trying to select a particular list item from elements in an unordered list. It should appear as selected, which I need to show by changing some background.

我正在尝试使用$index,它与我在<li>元素中使用它时一样未定义.

I was trying to use $index which comes as undefined as I was trying to use it within the <li> element.

我可以在angularjs内部实现此功能,而无需使用复选框或jQuery吗?

Can I achieve this from within angularjs, without using a checkbox or jQuery?

推荐答案

这取决于您的特定需求,但也许您可以像这样直接在项目中写入选择结果

It depends on your particular need but maybe you can write the result of the selection directly in the item like so

<ul>
    <li ng-repeat="item in items" ng-class="{'selected':item.selected}">
        <a href="" ng-click="toggle(item)">{{item.text}}</a>
    </li>
</ul>

其中

$scope.toggle = function (item) {
    item.selected = !item.selected;
};

在此处查看简约演示: http://jsfiddle.net/9qLm4/1/

See a minimalist demo here : http://jsfiddle.net/9qLm4/1/

或者您也可以使用$index这样将您的选择存储到其他array

Or you could use $index to store your selection into a different array like so

<ul>
    <li ng-repeat="item in items" ng-class="{'selected':selection.indexOf($index)!=-1}">
        <a href="" ng-click="toggle($index)">{{item}}</a>
    </li>
</ul>

其中

$scope.selection = [];

$scope.toggle = function (idx) {
    var pos = $scope.selection.indexOf(idx);
    if (pos == -1) {
        $scope.selection.push(idx);
    } else {
        $scope.selection.splice(pos, 1);
    }
};

在此处查看简约演示: http://jsfiddle.net/j5T2y/2/

See a minimalist demo here : http://jsfiddle.net/j5T2y/2/

我更喜欢前者,后者更为一致.

I have a preference for the former, which is more consistent.

这篇关于使用angularjs选择多个列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆