[email protected]      beta
Donate

AngularJs ng-include directives

Overview: Understanding ng-include directive, Use of AngularJS ng-include directives with an example, With ng-inculde directive we can embed HTML pages within an HTML page in angularjs.

What is ng-include directives in Angularjs?

The ng-include directives is used to add external html file into the main HTML pages. i.e we can embed HTML pages within a HTML pages. This directives can be used to inject angular code from external files into our main HTML page.

If we have an HTML page which contains some logic written in angularjs code, and we want that logic in another page. Then using ng-include, we can achieve it.

The default behavior of using ng-include will only work, if the included file would be from the same domain else ng-include will not work.

To use ng-include with cross domain, we need to add a whitelist of legal files or domains in the config function on our application.


Example 1: Using ng-include directive in AngularJs.

Here in this example, we have two HTML files, i.e., menu.html and main.html. In the menu.html page we have added some menus, and using ng-include we will display its content on our main.html page. The final code looks like as written below.

<!-- menu.html -->
<div>
    <ul>
        <li>Menu one</li>
        <li>Menu two</li>
        <li>Menu three</li>
        <li>Menu four</li>
    </ul>
</div>

<!-- main.html -->
<div ng-app="myApp">
    <div ng-include="'menu.html'"></div>
    This is our content blah blah
</div>

Example 2: Using ng-include directive with angular code file.

Here in this example, we have three files menu.html, admin.html, staff.html. In the menu.html page, we generate menus dynamically using ng-repeat directives. Now we included menu.html file within admin.html, staff.html and based on logic respected menus gets added. The final code looks like as written below.

<!-- menu.html-->
<div ng-app="myApp">
    <ul ng-repeat="x in myMenus">
        <li>x</li>
    <ul>
</div>

<!-- admin.html-->
<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-include="'menu.html'"></div>
    This is admin page
</div>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
            $scope.myMenus = [adminMenu1,adminMenu2,adminMenu3,adminMenu4]
    });
</script>


<!-- staff.html-->
<div ng-app="myApp"  ng-controller="myCtrl">
    <div ng-include="'menu.html'"></div>
    This is staff page
</div>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
            $scope.myMenus = [staffMenu1,staffMenu2]
    });
</script>

  Popular Tag
  Recent Posts
  Follow Us
If you find these tutorials helpful then please donate. It will lead me to do more tutorials.
Donate