angular - Switch navbar when view is changed

5.7k views Asked by At

I am using angular-route.min.js and I have two designs for my navbar.

The First one is the landing page navbar that will appear first on my index.html. enter image description here

The second navbar is when the user is routed to the /signin page.enter image description here

I am unsure on how to go about this. I see a lot of different ways that this could be done, but none really that explain how I could change the entire header view when another route is chosen. They just show how to change the links that are contained inside of it. Like this Stack

how can I switch out the header when it is routed to the /signin page?

also, I am working with another person who is doing the backend with Django. That is why I changed the "{{ }}" to "[[ ]]".

var app = angular.module('app', ['ui.bootstrap', 'ngRoute']);

app.config(function($interpolateProvider, $routeProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');

  $routeProvider

    .when('/', {
    templateUrl: 'pages/LandingPage.html',
  })

  .when('/signin', {
      templateUrl: 'pages/SignIn.html'
    })
    .when('/contact', {
      templateUrl: 'pages/contact.html'
    });
});
<!DOCTYPE html>
<html lang="en" data-ng-app="app">

<head>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
  </script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js">
  </script>
</head>

<body>
  <div ng-view></div>
</body>

</html>

2

There are 2 answers

3
yazaki On BEST ANSWER

I think ng-include directive could solve the situation you are facing.

In controller code.

.controller('HeaderCtrl', function($scope, $location) {
    $scope.$on('$locationChangeSuccess', function(/* EDIT: remove params for jshint */) {
        var path = $location.path();
        //EDIT: cope with other path
        $scope.templateUrl = (path==='/signin' || path==='/contact') ? 'template/header4signin.html' : 'template/header4normal.html' ;
    });
})

In Html.

<body>
    <div ng-controller="HeaderCtrl">
        <div ng-include="templateUrl"></div>
    </div>
    <div ng-view></div>
</body>

I hope this could help you. :)

1
Joy On

The difference of your two navbars are not significant. An alternative is just use ng-class and ng-show to give different styles.

For example, in the navbar.html:

<nav>
    <span ng-show="isNormalPage">Inn</span>
    <img ng-class="{align-center: isNormalPage}">Logo</img>
    <span ng-show="isNormalPage">Sing in</span>
</nav>

In your JS file, add a flag to mark singin page:

.when('/signin', {
  controller: [$scope, function ($scope) {
      $scope.isNormalPage = false;
    };
  }]
})