Klinki
Klinki

Reputation: 1439

AngularJS directive using templateURL loaded template

I'm trying to create a directive which would dynamically add content of template into DOM. Just like angular-datePicker does.

I would like to have such a directive as an attribute directive. I would use it for example for button. When button is clicked, form shows up. Technically I was thinking about using link function, binding a callback to element onClick event and add template content inside that callback using element.insertAfter method.

Problem is, I don't have access to template loaded by templateURL. And second problem is default behaviour of attribute directive - it automatically appends template as a child of the element. Is there any way how to disable it?

Upvotes: 0

Views: 687

Answers (1)

Ben Jacobs
Ben Jacobs

Reputation: 2526

It sounds like you want a little more custom behavior, and this is totally easy to script within your directive.

Basic steps:

  1. fetch the template using the $http service
  2. compile the template - referencing scope
  3. insert template wherever you want into the DOM

    angular.module('myModule').directive('myDirective', function ($http, $compile) {
        var directive = {};
    
        directive.restrict = 'A';
        directive.link = function (scope, elem, attr) {
            var templateString = '';
    
            $http.get('[ path to template ]').then(function (response) {
                templateString = response.data;
    
                var compiledHtml = $compile(templateString)(scope); // compile with scope variables
    
                element.append(compiledHtml); // change this around to insert your element into the DOM
            });
    
        };
    
        return directive;
    });
    

Upvotes: 1

Related Questions