I'm currently developing a module that will dynamically generate a menu. I am looking for guidance on how to execute a directive after adding new <li>
elements with the css class dropdown
, which is also added through ng-class.
Here is the code snippet:
angular.module('myapp', ['ui.bootstrap'])
.factory("menuService", ["$rootScope", function($rootScope) {
"use strict";
return {
menu: function() {
$rootScope.globalMenu;
},
setMenu: function(menu) {
$rootScope.globalMenu = menu;
}
};
}])
.controller("MainController", ["$scope", "menuService",
function($scope, menuService){
menuService.setMenu([{href:"#", label:"Dropdown",
dropdown:[{href:"/edit", label:"Edit"}]},
{href:'/', label:'test'}]);
$scope.bodyText = "Some text";
}]);
This HTML code snippet is as follows:
<ul class="navbar-nav nav navbar-left">
<li ng-repeat="menu_element in globalMenu" ng-class="{dropdown: menu_element.dropdown != undefined}">
<a ng-href="{{menu_element.href}}" ng-class="{'dropdown-toggle': menu_element.dropdown != undefined}">
{{menu_element.label}}
<b class="caret" ng-if="menu_element.dropdown != undefined"></b>
</a>
<ul ng-if="menu_element.dropdown != undefined" class="dropdown-menu">
<li ng-repeat="sub_element in $parent.menu_element.dropdown">
<a ng-href="{{sub_element.href}}">{{sub_element.label}}</a>
</li>
</ul>
</li>
</ul>
To view the code snippet in action, visit this link: http://plnkr.co/edit/pgH35mmsjLJqV4yJuSYq?p=preview
My goal is to achieve functionality similar to running $("li.dropdown").dropdown()
in jQuery after adding all the ul>li blocks dynamically. Since I am new to AngularJS, I am seeking advice on how to accomplish this in an angular way.
I have researched directives and their usage, but I have not been able to determine how to apply a directive at runtime. While exploring the transclude: element
feature in a directive like ui.bootstrap.dropdownToggle, it does not seem to be what I need. I am confident there is a straightforward solution out there, but I have yet to discover it on my own...