ngInclude Directive In AngularJS

In this article, you will learn about ngInclude directive in AngularJS.

ngInclude

This is used to include the external HTML fragments in the page and this tag is referenced. This is another example of the reusablity wherein, if HTML fragment is required on more than a page, HTML page is created and attached to the ng-include directive, as shown below.

This directive takes an Angular expression and treats it as a path to an HTML file. It then fetches the content from the Server and includes the content as a child of the element, where ng-include is placed.

The general syntax for including a page would be,

syntax

Let us define each of the properties, as shown in the syntax, mentioned above.

  1. Src is used to define the page which needs to be included in the caller page.

    syntax

    Or the code, mentioned above, can be written, as shown below:

    code

    Note: The name mentioned in ngInclude should be kept in singlequotes and doublequotes. In both cases, a literal is defined, as shown in the image, shown above, else if a variable is referred, it should be in double quotes, as shown below, where I have defined the page to be included in ngInit and the variable is referred to in the ngInclude directive.

    code

  2. Onload is used to call a function or an expression is required as a value such as if I want to have a function called, which will have the title of the called page i.e. included HTML fragment, as shown below:

    code

    code

    code

  3. Autoscroll is used, if on the page, it needs to be defined. The on load page should autoscroll to a particular tag in the included page. This property can be used, wher in the value of this property requires an expression, which should return true or false.

By default, the value of the property is false and this is an optional property for ngInclude directive.

Lets see an example for the same.

Suppose, I have included a page, which is having the records and page has a vertical scrolling on the same, as shown in the image, given below:

page

Now, I want to autoscroll to div, defined below this grid. As soon as the page loads, I can set the autoscroll property as true, as shown below;
page

Setting the property of autoscroll is shown below:
 
property

The controller code to autoscroll onload is shown below:


:property

If the property is set to true, this would autoscroll to the div and if it is set to false, it will not autoscroll to div defined.

Limitations of ng-include

If we are using any variable which is used in the main page and has to be accessed inside the included pages, the file can be dependent on one controller and cannot be used by other controllers. Due to these limitations of ngInclude, instead of using ngInclude, we need to create the custom directive.

I will be posting the article on the same, very soon, which will make it clear that the custom directives are very helpful and can overcome the limitations of ngInclude.