【问题标题】:wait to load angularjs directive template等待加载 angularjs 指令模板
【发布时间】:2013-02-15 22:05:56
【问题描述】:

我正在尝试做的是推迟加载指令的角度 js 模板,直到我真正需要它。我什至可能根本不需要它。有没有一种方法可以仅在需要时才加载指令的模板。服务会是做到这一点的方法吗?我的应用程序已经加载了很多指令模板,除非我需要,否则我想避免加载太多东西。手头的确切问题是为登录表单加载模板。如果用户点击一个按钮并且他/她没有登录我想slideOpen(使用jQuery)一个登录表单。

【问题讨论】:

  • 可以做到,但需要做一些工作。指令模板通常真的很小,我无法想象登录表单会很小。为什么要异步加载?
  • 只是想知道是否有好的方法。我同意登录表单很小,但我在想,如果这很容易做到,我会尝试一下。我应该补充一点,我不会回避困难的事情,所以如果有办法做到这一点,我想知道,因为它会增加我对 angular 的一般理解。

标签: angularjs


【解决方案1】:

在绝大多数情况下,动态加载静态指令模板没有任何价值。它们是如此之小,以至于这样做没有意义。但是,这是可能的。但是,大多数情况下,此策略用于动态模板。

它需要$http 来获取模板并需要$compile 将其连接到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 证明它有效。

【讨论】:

    【解决方案2】:

    你为什么不试试 ng-if 在指令上。

    <your-directive ng-if='userLoggedIn'></your-directive>
    

    在你的控制器中

    app.controller('yourCtrl', function($scope, service){
        $scope.dataHasLoaded = false;
    
        service.yourUserLoginFuntion(params).then(function (data) {
             //your login api
             $scope.userLoggedIn = true
        });
    });
    

    其中范围变量userLoggedIn 仅在您需要加载指令时才为真。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多