Changing Navigation Menu using UI-Router in AngularJs

后端 未结 2 1187
情书的邮戳
情书的邮戳 2021-01-13 19:31

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 Usern

相关标签:
2条回答
  • 2021-01-13 19:54

    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

    0 讨论(0)
  • 2021-01-13 19:56

    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.

    0 讨论(0)
提交回复
热议问题