AngularJS > Conditional Display

Include in AngularJS

How to include external file into web page using AngularJS?


Think about server side scripting language like Classic ASP, ASP.NET Web Forms or ASP.NET MVC, all had either include file or user control or partial view to make portion of code resusable and easily maintenable.

The same can be implemented here with the help of ng-include directive.

In below code snippet, we have a drop down with 2 items containing the html file path to include and ng-model set as "includeFile". This drop down also has initial value set to the first item value of the drop down value. After that we have a text box with ng-model as "MyName" and the same is being written within the paragraph.

<div ng-app>
    <select ng-model="includeFile" ng-init="includeFile = '/DemoSupportingFiles/angular-includefile1.html'">
        <option value="/DemoSupportingFiles/angular-includefile1.html">File 1</option>
        <option value="/DemoSupportingFiles/angular-includefile2.html">File 2</option>
    </select>

    <p>
        Write yoru name here <input type="text" ng-model="MyName" />
    </p>
    <p>
        My name is {{ MyName }}
    </p>
    <div style="border:1px solid #808080;" ng-include="includeFile">

    </div>
</div>

In the last part of the code snippet, we have a <div> element with ng-include directive whose value is set to the ng-model specified in the drop down (<select>.

Now, when the drop down value changes, its model (includeFile) gets changed that reflects into ng-include directive in the last <div> that internally calls the include file based on what value is selected in the drop down.

Important: Note that we have also bounded the value of the text box in the include file so when the text box value changes, the include file also gets updated. The text box model can be referenced to the include file either by prefixing $parent or directly referencing the ng-model of the text box.

Warning: If the file to include exists in different domain, we will not get expected functionality due to same origin policy from browser.

Below are code snippet of the include file referenced above.

/DemoSupportingFiles/angular-includefile1.html

<h1>File 1</h1>
<div style="padding:5px;">
    My name is {{ $parent.MyName }}
</div>

/DemoSupportingFiles/angular-includefile2.html

<h1>File 2</h1>
<div style="padding:5px;">
    My name is {{ MyName }}
</div>

Output

Include in AngularJS

 Views: 7755 | Post Order: 46




Write for us






Hosting Recommendations