AngularJS is an open-source JavaScript framework widely used to create single-page web applications. It has the built-in ng-include
directive to include different functionalities from external files. These files are appended as child nodes to the specified element.
<div ng-include="'filename'"> </div>
Note: Single quotes i.e.,
' '
are used to wrap the path of the file.
Now, we will look more into its functionality with the help of an example. Let's assume we have a file named navbar.html
.
<nav><button class="home">Home</button><button class="about">About</button><button class="register">SignUp</button></nav><style>nav{display: flex;justify-content:space-around;margin:auto;height: 5vw;background-color: lightgrey;border: 1px solid transparent;border-radius:5px;}button{width:10vw;text-align:center;background-color:transparent;border: 1px solid transparent;cursor: pointer;border-radius:5px;}button:hover{background-color:white;color:black;}</style>
We want to use this file in our main application. Therefore, we'll use the ng-include
directive to complete this task.
<nav> <button class="home">Home</button> <button class="about">About</button> <button class="register">SignUp</button> </nav> <style> nav{ display: flex; justify-content:space-around; margin:auto; height: 5vw; background-color: lightgrey; border: 1px solid transparent; border-radius:5px; } button{ width:10vw; text-align:center; background-color:transparent; border: 1px solid transparent; cursor: pointer; border-radius:5px; } button:hover{ background-color:white; color:black; } </style>
We have included the navbar which was defined in another file. We included that file in our index.html
file using the ng-include
directive.
Line 6–10: We add styles to the page components.
Line 12: We use the ng-app
directive to show the root element because ng-include
appends the file content as a child of the root element.
Line 14: Here, we specify the file name we want to include. The file's path is given and its content is added to the page.
Free Resources