AngularJS > Directives

Function with templateUrl in AngularJS

How to create a custom directive with templateUrl that returns a function in AngularJS?


In the previous post, we learnt how to create a custom diretive that returns a templateUrl and bind the data. In this post, we shall learn how to change the templateUrl for the custom directive dynamically based on elements attribute.

Notice the <script> block code, we have defined a controller with $scope properties username and address.

Next we have created a directive named 'my-custom-url-function' (its normalized name is myCustomUrlFunction) whose return is specified as templateUrl that in tern return a function. In this function, we are returning the url based on the "number" attribute value.

<script>
    var app = angular.module("app", [])
    .controller("CustomDirectiveController", function ($scope) {
        $scope.username = "SheoNarayan";
        $scope.address = "Hyderabad, India";
    });

    app.directive('myCustomUrlFunction', function () {
        return {
            templateUrl: function (element, attribute) {
                return '/DemoSupportingFiles/angular-MyView' + attribute.number + '.html';
            }
        };
    });
</script>

<div ng-app="app" ng-controller="CustomDirectiveController">
    <h2>function with templateUrl</h2>
    <div my-custom-url-function number="1"></div>
    <div my-custom-url-function number="2"></div>
</div>

The HTML code is preety simple and using the above created "my-custom-url-function" directive with "number" as attribute.

When the application runs, the first directive returns '/DemoSupportingFiles/MyView1.html' template file and second directive returns '/DemoSupportingFiles/MyView2.html' template file and shows the output in the browser.

MyView1.html

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

MyView2.html

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

Output

templateUrl with function

 Views: 23863 | Post Order: 36




Write for us






Hosting Recommendations