DWQA QuestionsCategory: ProgramHow to add a class by clicking Li in angularjs, and then click Remove class again without mutual influence
jersey asked 2 months ago
<!DOCTYPE html>
<html ng-app="myapp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script></script>
    <script>
    var m1 = angular.module('myapp',[]);
        m1.controller('Aaa',function($scope){
            $scope.colors = [{
                'id':'1',
                'name':'red'
            },{
                'id':'2',
                'name':'green'
            },{
                'id':'3',
                'name':'blue'
            }];
        });
    </script>
</head>
<body>
    <div ng-controller="Aaa">
        <ul>
            <li ng-repeat="color in colors">{{color.name}}</li>
        </ul>
    </div>
</body>
</html>

Do you need to use ID to correspond?

3 Answers
Best Answer
zhoulijun answered 2 months ago

It’s not as complicated as upstairs.

<ul>
    <li ng-class="{red : color.active}" ng-click="color.active = !color.active" ng-repeat="color in Texture">{{color.value}}</li>
</ul>
Treri answered 2 months ago

The subject should use angular directive to achieve this requirement
Result:http://output.jsbin.com/rolobakaya

javascriptm1.directive('toggleClass', function(){
    return {
        restrict: 'A',
        scope: {
            toggleClass: '@'
        },
        link: function($scope, $element){
            $element.on('click', function(){
                $element.toggleClass($scope.toggleClass);
            });
        }
    };
});
html<li toggle-class="classname"></li>
leozdgao answered 2 months ago

My thinking is:

<li ng-class="{active: currentId == color.id}" ng-repeat="color in colors">{{color.name}}</li>

Then define ang-clickAnd modify it in it$scope.currentId

leozdgao replied 2 months ago

http://jsbin.com/gonupe/edit?html,css,js,outputMake a simple demo, click Li to see the effect