samurai samurai - 3 months ago 38x
AngularJS Question

Dynamicly added dropdown menu in AngularJS + Bootstrap

I'm writing a module that will create a dynamic menu on the fly. How to run a directive after adding new

with css class
which is also added by ng-class.

The code:

angular.module('myapp', ['ui.bootstrap'])
.factory("menuService", ["$rootScope", function($rootScope) {
"use strict";

return {
menu: function() {
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 is the code in html

<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}">
<b class="caret" ng-if="menu_element.dropdown != undefined"></b>
<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>

Link to plunker:

So what I want to do is the same or similar as for jQuery, there I would run
after adding whole ul>li blocks. I'm new to Angular and I want to make this in the angular way.

I read about directives, how to use them. But I couldn't find how to apply directive in runtime. I've read about
transclude: element
in a directive (ui.bootstrap.dropdownToggle) doesn't have it enabled. I'm sure that there is a easy way, but couldn't find it myself...



I've finally made it with ng-if and ng-repeat-start. With help in comments, I've found that ng-class does not run directives.

    <ul class="navbar-nav nav navbar-left">
        <span ng-repeat-start="menu_element in globalMenu"></span>
        <li ng-if="menu_element.dropdown !== undefined">
              <a ng-href="{{menu_element.href}}" class="dropdown-toggle">
                  <b class="caret" ></b>
              <ul class="dropdown-menu">
                  <li ng-repeat="sub_element in $parent.menu_element.dropdown">
                      <a ng-href="{{sub_element.href}}">{{sub_element.label}}</a>
        <li ng-if="menu_element.dropdown === undefined">
              <a ng-href="{{menu_element.href}}">
        <span ng-repeat-end></span>

Working example on Plnkr. Something happened with the css on Plunker, yesterday it was working... but still it works.