wsfuller
wsfuller

Reputation: 1840

Remove Class AngularJS

Spent some time searching for an answer to this, grabbed a few lines of different sample code and it just errors out as well.

Goal:

Click a button > button adds class "active" to a div. Inside the div.active there is another element with a function to remove .active from div.active

HTML:

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <button ng-click="slidePanel='active'">Open Div 1</button>
    <div class="div1" ng-class="slidePanel">
        <div class="close" ng-click="removeActive()">Close</div>
        Hi I'm a Slide Panel
    </div>
  </div>
</body>

JS:

 angular.module('myApp', [])
.controller('myCtrl', ['$scope', function ($scope) {

$scope.removeActive = function () {

    //Errors with Element is not defined
    /*var myEl = angular.element(element.getElementsByClassName('div1'));
    myEl.removeClass('active');*/


    //Errors with myEl.removeClass is not a function
    var myEl = document.getElementsByClassName('div1');
    myEl.removeClass('active');

    //Errors with [jqLite:nosel] Looking up elements via selectors is not supported by jqLite!
    /*var myEl = angular.element('div1');
    myEl.removeClass('active');*/



    //Errors with Element is not defined
    /*var query = element[0].querySelector('.div1');
    var wrappedQueryResult = angular.element(query);
    query.removeClass('active');*/

}
}]);

Not sure what I'm doing wrong here.

FIDDLE

Upvotes: 0

Views: 2048

Answers (2)

Matthew Clise
Matthew Clise

Reputation: 191

If you don't want to use object notation (which would be my preferred method), you could also just set slidePanel back to an empty string to remove the class.

<div class="close" ng-click="slidePanel=''">Close</div>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

Solution is simpler if you use object syntax for ng-class

    <button ng-click="slidePanel=!slidePanel">Toggle Div 1</button>
    <div class="div1" ng-class="{active:slidePanel}">
        <div class="close" ng-click="slidePanel=!slidePanel">Toggle</div>
        Hi I'm a Slide Panel
    </div>

DOM manipulation should not be done in a controller. Always think scope first, angular has a huge array of tools to manage the dom based on scope models

What ng-class="{active:slidePanel} is doing is toggling the class active based on the expression slidePanel

DEMO

Upvotes: 1

Related Questions