How to change main layout in angular js?

Issue

When using ngRoute angular injects the views/templates into main layout i.e index.html. I don’t want angular to inject into index but to index into home.html. How can I achieve this?

Solution

Angularjs ngRoute is limited to one view outlet (as far as I know) so that you can only have one layout per app. However, there is the ui-router which is an alternative to application routing in angularjs, but in this case it supports sub routes (a.k.a., substates).

For example:

angular
  .module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {

    $stateProvider
      // /
      .state('app', {
        abstract: true,
        template: `
          <h1>Main</h1>
          <nav>
            <a ui-sref="app.home" ui-sref-active="active">Go Home</a>
            <a ui-sref="app.admin.dashboard" ui-sref-active="active">Go Admin</a>
          </nav>
          <ui-view></ui-view>
        `
      })
      // /home
      .state('app.home', {
        url: '/home',
        template: `
          <h2>Home</h2>
          <p><em>To be, or not to be, that is the question</em></p>
        `
      })
      // /admin
      .state('app.admin', {
        url: '/admin',
        abstract: true,
        template: `
          <h2>Admin</h2>
          <nav>
            <a ui-sref="app.admin.dashboard" ui-sref-active="active">Dashboard</a>
            <a ui-sref="app.admin.reports" ui-sref-active="active">Reports</a>
          </nav>
          <main>
              <ui-view>Substates goes here</ui-view>
          </main>
        `
      })
      // /admin/dashboard
      .state('app.admin.dashboard', {
        url: '/dashboard',
        template: `
          <h3>Dashboard</h3>
          <p>Expecting any charts?</p>
        `
      })
      // /admin/reports
      .state('app.admin.reports', {
        url: '/reports',
        template: `
          <h3>Reports</h3>
          <table border=1 cellspacing=0 cellpadding=2>
            <tr>
              <th>Head</th>
              <th>Head</th>
              <th>Head</th>
            </tr>
            <tr>
              <td>Item</td>
              <td>Item</td>
              <td>Item</td>
            </tr>
            <tr>
              <td>Item</td>
              <td>Item</td>
              <td>Item</td>
            </tr>
          </table>
        `
      });

    $urlRouterProvider.otherwise('/home');
  });
<div ng-app="app">
  <ui-view></ui-view>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>

Ref.: ui-router docs for Angularjs

Answered By – lenilsondc

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.