0

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?

1 Answer 1

1

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;
    });
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.