jqueryangularjsms-accesssidenav

MDB sideNAV button not working when added with jQuery


I am starting angular js application with MDB I have placed sideNav handler in html as below

<div class="float-left">
    <a href="#" data-activates="slide-out" ng-click="navCollapse()"
       class="button-collapse white-text"><i class="fas fa-bars"></i>
    </a>
</div>

in js code I tried to put evenHandler inside $().ready() and also in onDeviceReady

$(function(){
    //NOT WORKING
    $(".button-collapse").sideNav();

});

function domLoaded(){
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady(){
    //NOT WORKING
    //$(".button-collapse").sideNav();
}

then I tried on ng-click() as below

$scope.navCollapse = function(){
    $(".button-collapse").sideNav();
}

now it is working but with bugs
1- not working on first click
2- on second times loads to modaloverlays, on thrid time loads 3 overlays, so on clicking outside to hide sidenav and only one overlay gets disappear while other overlays remains there.


Solution

  • The reason that code adding jQuery event handlers at document ready often fail is that the AngularJS framework has not yet added the elements to the DOM. AngularJS directives such as ng-view, ng-repeat, ng-include, ng-when, ng-if, etc. add and remove DOM elements during the life of the app. If the framework has not yet added those elements at document ready, the jQuery code will not find those elements.

    To make sure the code is executed when the AngularJS framework adds the element to the DOM, add it as a directive:

    app.directive("sideNavDirective", function() {
        return {
            link: postLink
        };
        function postLink(scope, elem, attrs) {
            elem.sideNav();
        }
    })
    

    Usage

    <div class="float-left">
        <a href="#" data-activates="slide-out" side-nav-directive
           class="button-collapse white-text"><i class="fas fa-bars"></i>
        </a>
    </div>
    

    Be sure to load the jQuery library before loading angular.js.

    For more information, see