I am trying to build an animated hamburger menu icon. Everything is finished and works except the element.bind applies the active class only on every other ng-click (this is the essence of the animation). When I put console.log into the $scope.animateHamburger, it gets printed every time. Please see the code below where I also list what the console log returns.
controllers.js
$scope.animateHamburger = function() {
$scope.button = angular.element(document.getElementsByClassName('c-hamburger')[0]);
$scope.button.bind('click', function() {
$scope.button.toggleClass('is-active');
});
};
html
<button class="c-hamburger" ng-click="animateHamburger()" menu-toggle="left">
<span>toggle menu</span>
</button>
css (if needed)
/*** Hamburger button ***/
.c-hamburger {
background: transparent;
border: none;
height: 44px;
position: relative;
top: -21px;
text-indent: -9999px;
width: 48px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.c-hamburger:focus {
outline: none;
}
.c-hamburger span {
background: #fff;
display: block;
height: 2px;
left: 9px;
position: absolute;
right: 4px;
top: 21px;
}
.c-hamburger span::before,
.c-hamburger span::after {
background-color: #fff;
content: "";
display: block;
height: 2px;
left: 0;
position: absolute;
width: 100%;
transition-duration: 0.3s, 0.3s;
transition-delay: 0.3s, 0s;
}
.c-hamburger span::before {
top: -8px;
transition-property: top, transform;
}
.c-hamburger span::after {
bottom: -8px;
transition-property: bottom, transform;
}
/* active state, i.e. menu open */
.c-hamburger.is-active span {
background: none;
}
.c-hamburger.is-active span::before {
top: 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.c-hamburger.is-active span::after {
bottom: 0;
-webkit-transform: rotate(-45deg);
-ms=transform: rotate(-45deg);
transform: rotate(-45deg);
}
.c-hamburger.is-active span::before,
.c-hamburger.is-active span::after {
transition-delay: 0s, 0.3s;
}
/* Hamburger button */
console.log inside of $scope.animateHamburger after 4 successive clicks
Object { 0: <button.c-hamburger>, length: 1 } controllers.js
Object { 0: <button.c-hamburger>, length: 1 } controllers.js
Object { 0: <button.c-hamburger.is-active>, length: 1 } controllers.js
Object { 0: <button.c-hamburger.is-active>, length: 1 } controllers.js
Here is what should solve your issue:
<button ng-class="{'is-active': isActive, 'c-hamburger c-hamburger--htx': !isActive}" ng-click="isActive = !isActive" menu-toggle="left">
And no additional code is needed in controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.