2

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?

3
  • 2
    You're going to need to share your code if you want people to be able to advise you on your use case.... Commented Sep 14, 2013 at 1:25
  • 1
    You mean something like this? plnkr.co/edit/kuC3PK?p=preview Commented Sep 14, 2013 at 2:19
  • ^ That is a great plunker to get you going. I would personally use a directive in my <li> elements, and bind them to a click. That way you have more functionality available to you. Commented Sep 14, 2013 at 3:13

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Really appreciate your approach. But what if I want to add a click event on <li> element and not have a hyperlink. In that case you would not be able to have the value of index.
Should work with only a <li>. Modified example here : jsfiddle.net/djXVt/1
Thanks @ovmjm your answers helped me for my requirement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.