3

I would like to display the view name above the view
Basically, I am looking for something like

<h1>{{viewName}}<h1>
<div ng-view=""></div>

I have tried convoluted ways to get the view name from $routeProvider without much success.
My router looks like this

(function() {

  var app = angular.module("myModule", ["ngRoute"]);

  app.config(function($routeProvider) {
    $routeProvider
      .when("/view1", {
        name: "View One",
        templateUrl: "view1.html",
        controller: "View1Controller"
      })
      .when("/view2", {
        name: "View Two",
        templateUrl: "view2.html",
        controller: "View2Controller"
      })
      .otherwise({
        redirectTo: "/view1"
      });
  });

}());

My reasoning for displaying the view name outside the view is that the container (in this case ) would not be removed from the DOM at each view change, otherwise it flickers.

Am I using the right approach? How do you reach the "name" property inside $routeProvider?

JJJ
  • 32,902
  • 20
  • 89
  • 102
MonoThreaded
  • 11,429
  • 12
  • 71
  • 102
  • What makes you think routes have names? They don't. Angular will ignore the name attribute that you have added to the route definition. – JB Nizet Jul 05 '14 at 06:47
  • @JB_Nizet I made it up, I want to display a view specific name, whatever the location – MonoThreaded Jul 05 '14 at 06:47
  • 1
    Yes it's the right approach. Check this answer: http://stackoverflow.com/a/13407227/63011 – Paolo Moretti Jul 05 '14 at 06:49
  • Then specify it using the resolve attribute of the route definition, get the current route from the $route service, and get the name from the locals of the current route. The documentation will clarify this. – JB Nizet Jul 05 '14 at 06:50

1 Answers1

5

You could do something like this - by attaching to the $routeChangeStart event and putting the current route name on the $rootScope.

angular.module('myModule', ['ngRoute']).run([
    '$rootScope',
    function ($rootScope) {
        $rootScope.$on('$routeChangeStart', function (event, next) {
            $rootScope.currentRoute = next;
        });
    }]);

Then in your HTML you could do this:

<span>{{currentRoute.name}}</span>
Jon
  • 4,295
  • 6
  • 47
  • 56