Questions from angular noob. Templates in templates?

Hi,

I guess one way to do this would be to subscribe to route changes at rootscope and apply the name of the current controller to the class of the nav bar. E.g.:

<style>
  .MainController{
    display: none;
  }
</style>

<nav class="nav-bar" ng-class="controller" >
  <ul>
    <li><a href="#/">Main</a></li>
    <li><a href="#login">Login</a></li>
    <li><a href="#feed">Feedback</a></li>
  </ul>
</nav>

app.run(function($rootScope) {
  $rootScope.$on("$routeChangeSuccess", function(e, data) {
    $rootScope.controller = data.controller;
  });
});

Here’s an example you can run on your PC:

index.html

<!DOCTYPE html>
  <head>
    <title>App</title>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <style>
      .MainController{
        display: none;
      }
    </style>
  </head>

  <body ng-app="app">
    <nav class="nav-bar" ng-class="controller" >
      <ul>
        <li><a href="#/">Main</a></li>
        <li><a href="#login">Login</a></li>
        <li><a href="#feed">Feedback</a></li>
      </ul>
    </nav>

    <div class="page-wrapper">
      <div class="page" ng-view></div>
    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script>
    <script>
      'use strict';
      var app = angular.module('app', ['ngRoute']);

      app.config(function($routeProvider){
        $routeProvider.when('/', {
          templateUrl : 'templates/splash.html',
          controller  : 'MainController'
        })
        .when('/login', {
          templateUrl : 'templates/login.html',
          controller  : 'LoginController'
        })
        .when('/feed', {
          templateUrl : 'templates/feed.html',
          controller  : 'FeedController'
        });
      });

      app.run(function($rootScope) {
        $rootScope.$on("$routeChangeSuccess", function(e, data) {
          $rootScope.controller = data.controller;
        });
      });

      app.controller("MainController", function($scope){
        console.log("In Main");
      });

      app.controller("LoginController", function($scope){
        console.log("In Login");
      });

      app.controller("FeedController", function($scope){
        console.log("In Feed");
      });
    </script>
  </body>
</html>

templates/login.html

<h1>Login</h1>

templates/feed.html

<h1>Feedback</h1>

templates/splash.html

<h1>Splash</h1>

The view template to be rendered inside ng-view cannot contain another ng-view directive. This prevents you from creating nested views.

It might be worth looking at the angular-ui router, which (as far as I can recall), does support this.

1 Like