4

I am using MetisMenu with a dynamic <div>. When I load a new submenu under this <div>, the plugin stops functioning.

Is there any way to reset the plugin in the success part of my AJAX call? I've tried:

$('#menu').metisMenu({
   toggle: false // disable the auto collapse. Default: true.
});

but it's not working.

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
woshitom
  • 4,811
  • 8
  • 38
  • 62

2 Answers2

4

MetisMenu could not be called more than once because it calls init() function only once in its lifetime.

So it means if you are loading content of a element <div id="menu"> asynchronously using ajax and after that again binding event to <div id="menu"> by $('#menu').metisMenu(); won't make any difference.

So what you have to do is firstly destroy the existing metismenu event handler and then create a new one like below:

$('#menu').metisMenu('dispose'); //to stop and destroy metisMenu
$('#menu').metisMenu();

Below code is in angularjs

angular
  .module('app', [])
  .controller('menuCtrl', menuCtrl);

menuCtrl.$inject = ['$scope', '$http'];

function menuCtrl($scope, $http) {
  var url = "http://localhost/api/menus";

  $http.post(url)
    .success(function (data, status, headers, config) {

      // Destroy the existing metisMenu
      angular.element("#menu").metisMenu('dispose');

      //---- Update You div with data -----//

      // Create new binding
      angular.element("#menu").metisMenu();
    })
    .error(function (data, status, headers, config) {
      console.log("Error");
    });
}
Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
1

Calling

$('#menu').metisMenu()

should be sufficient to make MetisMenu aware of any new list elements that you have added via an AJAX call.

Make sure that you have added the new objects as <li> elements under the menu's <ul>. Also check that you have actually updated the DOM (and not just retrieved the new objects from the server) before invoking metisMenu.

(Note that the toggle option apparently does not change the initial appearance of the menu, which will initially be collapsed and require a click to expand.)

Myk Willis
  • 12,306
  • 4
  • 45
  • 62