Search code examples
javascripthtmlangularjsngroute

How to create a layout template for angular routing?


I use angular routing:

angular.module("app-test", ["ngRoute"]).config(function ($routeProvider, $locationProvider) {

    $locationProvider.hashPrefix('');

    $routeProvider.when("/",
        {
            controller: "firstController",
            templateUrl: "/views/first/index.html"
        });

    $routeProvider.when("/second",
        {
            controller: "secondController",
            templateUrl: "/views/second/index.html"
        });

    $routeProvider.otherwise({ redirectTo: "/" });
});

But all my views of the different routes (e.g. views/first/index.html, views/second/index.html, etc.) have repeating html code like loading panels, messages, etc. How can I outsource those common syntax in for example a layout html page that is used together with all the templateUrl views of the angular routing?

For example if every templateUrl has following html code - <div>{{message}}</div> - I would like to put this code in an extra html file which will be included in the templateUrl while the angular routing is getting the view.


Solution

  • You can use ng-include. But you can also use the same View (html) with different controllers:

            $routeProvider.when("/",
            {
                controller: "firstController",
                templateUrl: "/views/shared.html"
            });
    
        $routeProvider.when("/second",
            {
                controller: "secondController",
                templateUrl: "/views/shared.html"
            });
    

    Please also note that a "views" folder doesn't scale very well. It works better to have a feature directory for each feature that contains all the pieces needed to build that feature. Shared stuff can get a bit dicey--if you know in advance you're going to share it, you can put it in a "shared" or "common" directory, but sometimes you wind up using it from the feature where it was first used.