Skip to content

Instantly share code, notes, and snippets.

@lossendae
Last active July 4, 2019 20:22
Show Gist options
  • Save lossendae/8409675 to your computer and use it in GitHub Desktop.
Save lossendae/8409675 to your computer and use it in GitHub Desktop.
Dynamic (single level) menu for Angular ui-router
<!DOCTYPE html>
<html ng-app>
<head>
<title>Example</title>
</head>
<body>
<nav class="main-nav" data-main-menu data-root="index"></nav>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="ui.router.js"></script>
</body>
</html>
'use strict';
define(['app'], function (app) {
var mainMenu = function($state, $stateParams, commons) {
return {
restrict: 'A',
templateUrl: commons.path('views') + 'common/menu.html',
transclude: true,
compile: function(tElement, tAttrs) {
var root = tAttrs.root;
return function($scope, $elem, $attr) {
$scope.show = function(state){
if(!angular.isDefined(state.menu)){
return false;
}
if(!angular.isDefined(state.menu.icon)){
state.menu.icon = 'fa-link';
}
if(!angular.isDefined(state.menu.target)){
state.menu.target = state.name;
}
if(angular.isDefined(root)){
state.current = state.name == root ? $state.is(root) : $state.includes(state.name);
} else {
state.current = $state.is(state.name);
}
return true;
};
}
}
};
};
app.register.directive('mainMenu', ['$state', '$stateParams', 'commons', mainMenu]);
});
<ul>
<li data-ng-repeat="state in $state.get() | filter:show" data-ui-sref-active="current">
<a ui-sref="{{ state.menu.target }}"><i class="fa {{ state.menu.icon }}"></i>{{ state.menu.title }}</a>
</li>
</ul>
/* In my main config module */
// Shown in menu
$stateProvider
.state('index', {
url: "/",
menu : {
title : 'Dashboard',
icon : 'fa-home'
}
});
/* In another config module */
$stateProvider
// Not shown in menu
.state('index.item', {
url: "/item"
})
// Show in menu
.state('index.item.child', {
url: "/child1",
abstract: true
menu : {
title : 'A menu item',
state : 'index.item.child.grandchild' // Point to children
}
})
// Not shown in menu but a menu item point to it
.state('index.item.child.grandchild', {
url: ""
})
// Not shown in menu
.state('index.item.child.grandchild2', {
url: "/child2"
});
@benjiwheeler
Copy link

in state.js on line 24, what is going on with the syntax? isn't there a comma missing on line 23? and, i don't see a "menu" property available in the API, per the documentation: http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment