等待加载angularjs指令模板 [英] wait to load angularjs directive template

查看:110
本文介绍了等待加载angularjs指令模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是推迟加载JS角模板指令,直到我真的需要它。我可能甚至不需要它。有没有一种方式,如果我需要它,我也许可以只加载模板指令。将服务能够做到这一点的方式呢?我的应用程序已经加载了很多指令模板,我想,以避免加载太多的东西,除非我需要它。手头确切的问题是登录表单模板的加载。如果用户点击一个按钮,他/她没有登录我要slideOpen(使用jQuery)一个登录表单。

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.

推荐答案

在绝大多数情况下,是没有价值的动态加载静态指令模板。他们是如此之小,它只是没有意义去做。但是,这是可能的。然而,大多数时候,这种策略是用于动态模板。

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.

这需要 $ HTTP 来获取模板和 $编译将其连接到AngularJS。

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 ) {
          showTheDirective();
        }
      });

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

下面是一个 Plunker 证明它的作品。

Here's a Plunker demonstrating that it works.

这篇关于等待加载angularjs指令模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆