Seong Lee
Seong Lee

Reputation: 10520

ng-click and ng-class to toggle classes

I'm trying to accomplish toggling open class to nav element with button click. Below code does not assign open class to nav neither removing open when button is unclicked.

<nav class="slide-menu" ng-class="{'open': open, '': !open}">

<button class="slide-btn" ng-click="open=!open"></button>

I'm aware '' this is obviously wrong as it just assigns literal as class.

Upvotes: 2

Views: 1241

Answers (1)

HasanAboShally
HasanAboShally

Reputation: 18675

Try adding an ng-init to a container div:

<div ng-init="open=false">
    <nav class="slide-menu" ng-class="{'open': open}">
    <button class="slide-btn" ng-click="open=!open"></button>
</div>

Or add $scope.open = false; in your scope.

What happens in your above code is that each one of the two elements has it own scope, which contains a open property, so you can wrap them in another element (that has it's own scope) and place the open property there. so in the inner scopes of the nav and the button when it tries to look for a property called open it looks in it's own scope and don't find it, so it looks in it's parent scope (the wrapping div) and find it there.

You can understand more about angular scope inheritance from here: https://github.com/angular/angular.js/wiki/Understanding-Scopes

-- Also, you don't need the '': !open part.

Upvotes: 6

Related Questions