How to highlight a selected row in ngRepeat?

前端 未结 3 1950
Happy的楠姐
Happy的楠姐 2020-12-02 13:56

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

相关标签:
3条回答
  • 2020-12-02 14:49

    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

    0 讨论(0)
  • 2020-12-02 14:51

    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

    0 讨论(0)
  • 2020-12-02 14:51

    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/

    0 讨论(0)
提交回复
热议问题