AngularJs (1.X) Include Partial Template

AngularjsTemplatesIncludePartial

Angularjs Problem Overview


I've this in my main layout file

<body>
    <header id="header" ng-controller="HeaderController"></header>
    <div class="container" ng-view></div>

I've a header.html partial template in my directory structure.

How to include this template in my app? I thought angular automatically includes the template after processing the controller, but it doesnt work.

The header node should be replaced with the content of this file.

Angularjs Solutions


Solution 1 - Angularjs

One way of including templates/html fragments from external files is to use the ng-include directive (doc).

<ng-include src="'/path/to/the/header.html'"></ng-include>

or

<div ng-include src="'/path/to/the/header.html'"></div>

Solution 2 - Angularjs

From Angular 2, ngInclude has been removed and custom directives are preferred. This is the way I come up with

  1. Define the main component for your app, which link to the master page

         @View({
             templateUrl:   'client/app/layout/main.html',
             directives: [ROUTER_DIRECTIVES, Navigation, Footer]
         })
         @Component({selector: 'app'})
         @RouteConfig(
             routerConfig
         )
         class MainComponent {
         }
    

And this is the main template

<!---- Navigation bar ---->
<navigation></navigation>
<!----/ Navigation bar ---->

<!---- Main Part ---->
<router-outlet>
</router-outlet>
<!----/ Main Part ---->

<!---- Footer ---->
<footer></footer>
<!----/ Footer ---->

2. Define a base.html, which will contain the body tag and the app tag

<body> <app>Loading ...</app> </body>

  1. Now, final step is defining the components for Navigation and Footer like the MainComponent, which point to your partial templates

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3403716View Question on Stackoverflow
Solution 1 - AngularjsSuvi VignarajahView Answer on Stackoverflow
Solution 2 - AngularjsThai TranView Answer on Stackoverflow