Edgar Martinez Edgar Martinez - 1 year ago 136
AngularJS Question

wait to load angularjs directive template

What I am trying to do is postpone loading the angular js template for a directive until I really need it. I might not even need it at all. Is there a way that I can maybe only load the template for a directive if I need it. Would a service be the way to do this? My application already loads a lot of directive templates and I would like to avoid loading too much stuff unless I need it. The exact problem at hand is the loading of a template for a login form. If the user clicks on a button and he/she is not logged in I want to slideOpen (using jQuery) a login form.

Answer Source

In the vast majority of cases, there is no value to dynamically loading static directive templates. They are so small that it just doesn't make sense to do it. But, it is possible. However, most of the time, this strategy is used for dynamic templates.

It requires $http to fetch the template and $compile to wire it into AngularJS.

app.directive('testDirective', function($http,$compile) {
  return {
    scope: { show: '&' },
    link: function( scope, element, attrs ) {
      var tpl,
          url = 'testDirective.tpl.html';

      scope.$watch( 'show()', function (show) {
        if ( show ) {

      function showTheDirective () {
        if ( !tpl ) {
          $http.get( url ).then( function ( response ) {
            tpl = $compile( response.data )( scope );

Here's a Plunker demonstrating that it works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download