Ankit Ladhania
Ankit Ladhania

Reputation: 995

Changing Navigation Menu using UI-Router in AngularJs

I'm trying to build a navigational menu like any social networking site i.e. If i'm logged-Out i Can see the input fields asking for Username and Password but if I'm logged-In then i get to see my profile ,settings ,etc.

I'm trying to do the same thing but Cannot thing of an approach to this i Just need to know the way i can do this. I know the use case in which angular directive are used like ng-if ,etc but i'm thinking of using partials in some way.

I'm Using AngularJs with UI-Router.

Upvotes: 4

Views: 3992

Answers (2)

Radim Köhler
Radim Köhler

Reputation: 123861

The ui-router solution could be like in this plunker, I've created to show the ui-router way. There is no need to use some view rendering directives ala ng-if, ng-show... which in fact moves the logic from business into the view.

The example shows a comprehensive design, with redirections for unauthorized users, as well to grant the public accesss to anybody, supporting log on/off in one view, etc.

Better solution is to profit from built-in features of the ui-router, e.g.:

Templates (let me cite:)

TemplateUrl
... templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is NOT injected.

TemplateProvider
Or you can use a template provider function which can be injected, has access to locals, and must return template HTML...

So, what we can see in our example. Firstly there is a root state with two views, one of them is standard anchor, for all main child unnamed views ui-view=""

$stateProvider
.state('root', {
  abstract: true,
  views: {
    '': {templateUrl: 'tpl.root.html', },
    'loginfo@root': {
      templateProvider: templateSelector,
      controller: 'LoginCtrl',
    }
  }
})

where the templateSelector would be like this:

var templateSelector = function($http, UserService) 
{
  var templateName = UserService.isLogged
    ? "tpl.loggedin.html"
    : "tpl.loggedoff.html"
    ;

  return $http
    .get(templateName)
    .then(function(tpl){
      return tpl.data;
    });
};

Relying on simple setting in this example:

.factory('UserService', function() {
  return {
    isLogged: false,
  };
})

And that's it, we do have two templates:

  • "tpl.loggedin.html"
  • "tpl.loggedoff.html"

The remaining stuff is pretty expectable, state definitions, some redirection on unauthorized access... please observe the example.

which are interchanged based on the fact if user is logged on or off

Check the solution in this working plunker

Upvotes: 3

rmuller
rmuller

Reputation: 1837

You could use one of the following angular directives: ng-if, ng-show, ng-hide

Check in your controller if the user has signed in successfully and assign this value a ($scope) variable and use this as a condition to either show or hide certain elements of your navigation bar.

Upvotes: 0

Related Questions