[英]AngularJS Directive to add class on click, but remove and add it to another element if clicked
[英]How to add and remove a class if another element is clicked in AngularJS?
我尝试使用AngularJS ngClass
指令单击按钮时切换主体类。
我在按钮中添加了一个变量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>
然后我将要切换的类添加到主体:
<body class="ctr-hidden" ng-class="{'ctr-show': add, 'ctr-hidden': add}">
但它不起作用,因为它同时添加了'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.