0

I tried to toggle a class of body when a button is clicked by using the AngularJS ngClass directive.

I have added a variable ng-model="add" to the button:

<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'.

2 Answers 2

1

'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>

Sign up to request clarification or add additional context in comments.

Comments

0

I don't fully follow your question but surely you want something like

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

1 Comment

It does not look like an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.