0

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

0

2 Answers 2

1

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

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

2 Comments

The issue is I can't use ng-click="slidePanel=!slidePanel" in this particular instance. The reason is, once you click that button the div.active will slide over top. So would a custom directive be needed in this situation?
I did that for code simplification but it could be a function also that changes a scope variable or triggers an event or updates a service object
0

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>

Comments

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.