Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple list items using angularjs

Tags:

angularjs

list

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.

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

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

like image 913
Aditya Sethi Avatar asked Sep 23 '26 09:09

Aditya Sethi


1 Answers

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>

where

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

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

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>

where

$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);
    }
};

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

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

like image 54
ovmjm Avatar answered Sep 24 '26 23:09

ovmjm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!