I've a sample code to create a simple menubar here which works, but I'm not sure if that's the best way to code it. Can somebody please validate if there is a better way to do the same?
In short
I've create a sample page with a directive called
<menu-bar>
<menu-bar></menu-bar>
The directive merely points to a template code and a controller
app.directive("menuBar", function () { return { restrict: 'E', templateUrl: 'main-nav.html', controller: 'navController', controllerAs: 'nc' } });
The controller loads the menubar (which will eventually fetch the items from the DB
app.controller('navController', ['$scope', '$location', function ($scope, $location) { $scope.navigationTabs = [ new NAV("file","/file","File","fa fa-file-o", "active"), new NAV("edit","/edit","Edit","fa fa-edit", "inactive"), new NAV("view","/view","View","fa fa-search", "inactive"), new NAV("hist","/history","History","fa fa-history", "inactive"), new NAV("bmark","/bookmarks","Bookmarks","fa fa-bookmark-o", "inactive"), new NAV("hlp","/help","Help","fa fa-life-buoy", "inactive") ]; ... }]);
The controller defines a 'selectTab()' method which changes the url of the application when the user selects a menu-item. It also clears the active class on all the other items and sets the 'active' class on the one selected
... $scope.selectTab = function (nav) { $scope.navigationTabs.forEach(function (nav) { nav.active=""; }); console.log("navigating to url: " + nav.key); $location.path(nav.key); nav.active = "active"; }
The NAV item is defined in the app.js as follows:
var NAV = function (id, key, value, icon, active) { this.id = id; this.key = key; this.value = value; this.icon = icon; this.active = active; };