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>
    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'

<div ng-app="app" ng-controller="CustomDirectiveController">
    <h2>Custom directive with external page</h2>
    <div my-custom-url></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'.


<table class="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


Custom directive with external template page

 Views: 58036 | Post Order: 35

Write for us

Hosting Recommendations