Angularjs directive clicking elements

2019-09-02 04:36发布

问题:

Hi I was wondering when I have a list of elements from a ng-repeat, how I can allow the user to click one of the list and make it highlight via .css(). Then if the user clicks another element, the previous element un-highlights and the newly-clicked element highlights?

Thanks

回答1:

You may try to use ng-click to set the selected item and apply a conditional css class with ng-class:

<ul>
    <li ng-repeat="item in list" ng-class="{'highlight': model.selected == item}">
        <button ng-click="model.selected = item">Select</button>
    </li>
</ul>

In your controller:

$scope.model = { selected : null };

We need to use an object to hold the selected item so the scope is shared for every items of the ng-repeat, otherwise, it would exist for every items, therefore multiple items could be selected.

DEMO: http://plnkr.co/edit/EdrD7MvesW3xn9C9c6fk?p=preview