Search code examples
javascripthtmlcssangularjsmaterialize

Materializecss dropdown menu not working with AngularJS


I'm developing a web app using Materializecss and AngularJS for the front-end, my problem is that the dropdown menu component of materialize doesn't work for me.

Here's the example dropdown on their site

$( document ).ready(function(){
    $(".dropdown-button").dropdown();
});
<!-- Dropdown Structure -->
<ul id="dropdown1" class="dropdown-content">
  <li><a href="#!">one</a></li>
  <li><a href="#!">two</a></li>
  <li class="divider"></li>
  <li><a href="#!">three</a></li>
</ul>
<nav>
  <div class="nav-wrapper">
    <a href="#!" class="brand-logo">Logo</a>
    <ul class="right hide-on-med-and-down">
      <li><a href="sass.html">Sass</a></li>
      <li><a href="components.html">Components</a></li>
      <!-- Dropdown Trigger -->
      <li><a class="dropdown-button" href="#!" data-activates="dropdown1">Dropdown<i class="mdi-navigation-arrow-drop-down right"></i></a></li>
    </ul>
  </div>
</nav>

In their site it does work but in mine it doesn't and I'm guessing it has to do something with the href="#!" part of the dropdown button because maybe AngularJS is trying to map the route or something

If this is the problem then how can I make AngularJS ignore some of the hrefs? Because in order to do dropdowns and modals I need those href="#!", or if not, what's the problem, and how could I fix it?

I tried removing the href or changing it with href="", but that didn't work.


Solution

  • Be careful mixing frameworks, it can, and probably will have unexpected effects. As for showing and hiding elements, Here is a simple example of how to hide, show, or toggle any element.

    (demo)

    HTML

    <a href="javascript:void()" data-show="hidden">Show</a>
    <a href="javascript:void()" data-hide="hidden">Hide</a>
    <a href="javascript:void()" data-toggle="hidden">Toggle</a>
    <div id="hidden"><!-- This can be any type of element -->
        <!-- Anything in here -->
    </div>
    

    CSS

    #hidden {
        display: none;
    }
    

    JavaScript

    $("[data-show]").on("click", function () {
        $("#" + $(this).attr("data-show")).css("display", "initial");
    });
    $("[data-hide]").on("click", function () {
        $("#" + $(this).attr("data-hide")).css("display", "none");
    });
    $("[data-toggle]").on("click", function () {
        var target = $("#" + $(this).attr("data-toggle"));
        if (target.css("display") === "none") {
            target.css("display", "initial");
        } else {
            target.css("display", "none");
        }
    });
    

    I used jQuery here because you used jQuery in your script, this can be done easily in pure JavaScript as well. Make sure to put the JavaScript after the DOM, otherwise wrap the script in a document.onload handler.