简体   繁体   中英

How to add class in AngularJS on ng-click for multiple elements (smartly)?

I have 2 "lists" (in HTML). I want to make it so that any option I click, adds a class that changes the background-color of the li element to red. If any individual option is clicked again, then it removes the class (so the background reverts to white):

This is what the list looks like in my current HTML page/template:

List A

<ul>
    <li>Something 1</li>
    <li>Something 2</li>
</ul>

List B

<ul>
    <li>Otherthing A</li>
    <li>Otherthing B</li>
    <li>Otherthing C</li>
</ul>

My current state is having each li have it's own expression, with its own individual $scope variable that keeps track of true or false. (Individual $scope variable meaning. $scope.otherthingaclicked = true , $scope.otherthingbclicked = true , $scope.otherthingcclicked=false , etc.)

<li ng-class="expression">Otherthing A</li>

There has got to be a better way. How can I make this smarter?

Yes, there is a better solution to it. Here comes the usage of the Angular directives:

myApp.directive("toggleClass", function() {
    return {
        link: function($scope, element, attr) {
            element.on("click", function() {
                element.toggleClass("option-selected");
            });
        }
    }
});

Then, apply it to your li s:

<ul>
    <li toggle-class>Something 1</li>
    <li toggle-class>Something 2</li>
</ul>

And, your CSS:

li.option-selected {
    background: red;
}

 var myApp = angular.module("sa", []); myApp.directive("toggleClass", function() { return { link: function($scope, element, attr) { element.on("click", function() { element.toggleClass("option-selected"); }); } } }); 
 li.option-selected { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ul ng-app="sa"> <li toggle-class>Something 1</li> <li toggle-class>Something 2</li> <li toggle-class>Something 3</li> <li toggle-class>Something 4</li> </ul> 

Are you going to use (or save) the result of what li items the user has clicked? If you do so, you might need to save a boolean value for each li element.

//JS
$scope.listA = [
    { label: "Something 1", checked: false },
    { label: "Something 2", checked: false },
    { label: "Something 3", checked: false }
];

Then you use a ng-repeat and ng-click to handle it.

<!-- HTML -->
<ul>
    <li ng-repeat="item in listA" ng-class="{ 'selected': item.checked }">
        <a href="javascript://" 
            ng-click="item.checked = !item.checked">{{item.label}}</a>
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM