AngularJS > Directives

Custom directive with templateUrl in AngularJS

How to create custom directive with external template in AngularJS?


In the previous post, we learnt how to create custom directive with a small inline template.

When our template grows bigger for custom directive, its annoying and difficult to maintain them. In this case, we can keep our template for the custom directive in external page and load it with templateUrl option.

<h2>Directive Custom</h2>
<script>
    var app = angular.module("app", [])
    .controller("CustomDirectiveController", function ($scope) {
        $scope.username = "SheoNarayan";
        $scope.address = "Hyderabad, India";
    });
    
    app.directive('myCustomUrl', function () {
        return {
            templateUrl: '/DemoSupportingFiles/angularjs-details.html'
        };
    });


</script>
<div ng-app="app" ng-controller="CustomDirectiveController">
    <h2>Custom directive with external page</h2>
    <div my-custom-url></div>
</div>

In the <script> block, notice the highlighted code snippet where we have created a directive named "myCustomUrl" (equivalent to my-custom-url) that is using its template to write from external page '/Template/angularjs-details.html'.

angularjs-details.html

<table class="table">
    <tr>
        <th>Username</th><th>Address</th>
    </tr>
    <tr>
        <td>{{username}}</td><td>{{address}}</td>
    </tr>
</table>

Notice the above template page, where the {{username}} and {{address}} properties of $scope have been used to bind.

When the page loads, Angular downloads the template page angularjs-details.html page and binds the data of $scope that looks like below

Output

Custom directive with external template page

 Views: 16310 | Post Order: 35




Write for us