57

I couldn't find something that will help me to solve this simple issue in Angular. All the answers are relevant for navigation bars when a comparison is being made against location path.

I've built a dynamic table using list and ngRepeat. When I click a row I'm trying to assign this row a css class, selected, to highlight the fact that this row has been selected by user, and remove the .selected from previously highlighted row.

I'm missing the method to bind between the row that been selected and the css class assignment.

I applied on each row (ul) ng-click="setSelected()" But I'm missing the logic inside the function to apply the changes.

My Code - Plunk

My code:

var webApp = angular.module('webApp', []);

//controllers
webApp.controller ('VotesCtrl', function ($scope, Votes) {
    $scope.votes  = Votes;
    $scope.statuses = ["Approved","Pending","Trash","Spam"];

    $scope.setSelected = function() {
       console.log("show");

    }
});

//services
webApp.factory('Votes', [function() {

    //temporary repository till integration with DB this will be translated into restful get query
    var votes = [
        {
            id: '1',
            created: 1381583344653,
            updated: '222212',
            ratingID: '3',
            rate: 5,
            ip: '198.168.0.0',
            status: 'Pending',
        },
        {
            id: '111',
            created: 1381583344653,
            updated: '222212',
            ratingID: '4',
            rate: 5,
            ip: '198.168.0.1',
            status: 'Spam'    

        },
        {
            id: '2',
            created: 1382387322693,
            updated: '222212',
            ratingID: '3',
            rate: 1,
            ip: '198.168.0.2',
            status: 'Approved'

        },
        {

            id: '4',
            created: 1382387322693,
            updated: '222212',
            ratingID: '3',
            rate: 1,
            ip: '198.168.0.3',
            status: 'Spam'
        }
    ];

    return votes;
}]);

My HTML:

  <body ng-controller='VotesCtrl'>
    <div>
    <ul>
        <li class="created">
            <a>CREATED</a>
        </li>
        <li class="ip">
            <b>IP ADDRESS</b>
        </li>
        <li class="status">
            <b>STATUS</b>
        </li>
    </ul>
    <ul ng-repeat="vote in votes" ng-click="setSelected()">
        <li  class="created">
          {{vote.created|date}}
        </li>
        <li class="ip">
            {{vote.ip}}
        </li>
        <li class="status">
            {{vote.status}}
        </li>
    </ul>
   </div>
   </body>

My CSS (Only selected class):

.selected {
  background-color: red;
}

3 Answers 3

134

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

10
  • Well this solution IMO is better than the previous one. Oct 12, 2013 at 9:18
  • Is there any way to do this without using a controller? I am trying to find an 'optimal' way to do it in the view but I haven't had luck. I tried to do something like... ng-click="idSelectedVote = vote" ng-class="{selected:vote.id === idSelectedVote}" but upon clicking a row, other rows remain selected. Your solution works, but it would be nice if a view only solution existed.
    – Spencer
    Oct 3, 2014 at 22:59
  • 3
    @Spencer There's a new scope associated with each <ul> created by ngRepeat; therefore, idSelectedVote in your ngClick just modifies the local scope, and not the one shared with the others. Two solutions: use $parent.idSelectedVote instead (dirty, really!), or use an object (ng-init="selectedVote = {id: null}" in a <ul> ancestor) and only modify one of its properties, not the whole object (ng-click="selectedVote.id = vote.id"). Anyway, using the controller for that would always be a far better solution.
    – Blackhole
    Oct 4, 2014 at 9:09
  • A custom directive could be the optimal way of moving the logic outside of the controller, depending on how complex your app is and how crowded the scope becomes.
    – nikk wong
    May 17, 2015 at 2:57
  • 1
    @nikkwong Actually, that's usually a good idea to put the logic in the controller, unless your repeatedly use the same one, in which case a directive is well suited, indeed.
    – Blackhole
    May 17, 2015 at 13:11
6

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

2
  • 1
    I clicked up on this answer because I could get it to work and I couldn't get the checked one going. But you've got a couple of discrepancies between your code here and in your plunker. The ng-click above is missing the (this), and your class above has quotes around the property, but the plunker doesn't. Oct 26, 2013 at 1:13
  • After I posted the Plunker link I noticed that it was missing quotes, and that the this in the argument list was only used by the console.log. However, you can pass in the selected row, or use this, but should not use $scope as that is the scope for the whole VoteCtrl: plnkr.co/edit/JoSUwA?p=preview
    – user508994
    Oct 31, 2013 at 7:45
3

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

1
  • 1
    Please don't just link to external sites, blogs etc, even if you're the author - a good answer on stackoverflow contains the necessary details within the post itself.
    – bacar
    Aug 2, 2014 at 23:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.