Skip to content

Instantly share code, notes, and snippets.

@benjiwheeler
Created November 18, 2015 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjiwheeler/563245868f0f088ac898 to your computer and use it in GitHub Desktop.
Save benjiwheeler/563245868f0f088ac898 to your computer and use it in GitHub Desktop.
Angular navigation menu controller from Begin to Code
// see the very bottom of http://angular-rails.com/find_and_browse.html
// by omitting second parameter, we tell angular we're looking for existing module.
var controllers = angular.module('basicControllers');
controllers.controller('NavMenuCtrl', ['$scope', '$stateParams', '$state', 'ProgramCache',
function($scope, $stateParams, $state, ProgramCache) {
// variables
$scope.menuStates = []; // all of the menu items, each a complete state
// IMPORTANT: we are binding global program service to local program scope!
// this lets us update menu item content on the fly, since our template will be digested.
$scope.userId = 0;
// functions
// format an href so that target state gets a bunch of state params
$scope.menuStateHref = function(targetState) {
return $state.href(targetState, {
program_id: $scope.program.id,
user_id: $scope.userId
});
}
// new state has been navigated to, so we need to refresh menu item list
$scope.$on('$stateChangeSuccess', function() {
$scope.updateMenuItems();
});
// changes $scope.menuStates to be correct set of menu items for this state view.
// list to use comes from the data section of state definition in routes
$scope.updateMenuItems = function() {
var allStates = $state.get(); // get list of all states
$scope.menuStates = []; // clear list
if ($state.current.data !== null && $state.current.data !== undefined) {
if ($state.current.data.hasOwnProperty("menu")) {
// here's where we stop being careful and assume the menu data is formatted correctly
$scope.menuStates = _.map($state.current.data.menu.states, function(stateName) {
return _.findWhere(allStates, {
name: stateName
});
});
}
}
}
// since we shouldn't show an empty menu
$scope.isEmpty = function() {
var emptiness = ($scope.menuStates === null || $scope.menuStates === undefined || $scope.menuStates.length < 1);
log.debug("isEmpty? " + (emptiness ? "true" : "false"));
return emptiness;
};
// init
$scope.updateMenuItems();
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment