简体   繁体   English

如果在AngularJS中单击另一个元素,如何添加和删除类?

[英]How to add and remove a class if another element is clicked in AngularJS?

I tried to toggle a class of body when a button is clicked by using the AngularJS ngClass directive. 我尝试使用AngularJS ngClass指令单击按钮时切换主体类。

I have added a variable ng-model="add" to the button: 我在按钮中添加了一个变量ng-model="add"

<md-button aria-label="Add" class="md-icon-button" ng-model="wrong">
    <md-icon md-svg-icon="other:add" md-menu-align-target></md-icon>
</md-button>

Then I added to the body the classes to toggle: 然后我将要切换的类添加到主体:

<body class="ctr-hidden" ng-class="{'ctr-show': add, 'ctr-hidden': add}">

but it does not work, because it adds both the class 'ctr-show' and class 'ctr-hidden' . 但它不起作用,因为它同时添加了'ctr-show'类和'ctr-hidden'

 'use strict'; angular .module('app', []) .controller('ToggleClassCtrl', function($scope, $rootScope) { $rootScope.classIsSet = false; $scope.toggleClass = function() { $rootScope.classIsSet = !$rootScope.classIsSet; }; }); 
 .result-block.ctr-show { background-color: #00ff00; } .result-block.ctr-hidden { background-color: #ff0000; } .result-block { width: 200px; height: 200px; background-color: #0000ff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <div ng-app="app"> <div class="result-block" ng-class="{'ctr-show': classIsSet, 'ctr-hidden': !classIsSet}"> </div> <div ng-controller="ToggleClassCtrl"> <button ng-click="toggleClass()">Toggle the class</button> </div> </div> 

我没有完全关注您的问题,但是您肯定想要

<body ng-class="{'ctr-show': add, 'ctr-hidden': !add}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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