当惰性加载指令时,它'We’我们永远不要跑步

When lazy loading directive, it's never run

本文关键字:我们 We 永远 加载 指令      更新时间:2023-09-26

我正在尝试延迟加载指令。它被加载和定义,但之后它就再也不会在html上运行了。在指令被惰性加载后,我如何获得运行指令的角度?

.config(function ($compileProvider, routes, $provide) {
    //Lazy define
    $compileProvider.directive('myDirective', function ($rootScope, $location, $filter) {
        console.log( "This IS called" );
        return function (scope, element, attrs) {
          console.log( "This is NEVER called");
        }
    }
}

HTML:

<div my-directive></div>

如果我不懒惰地加载它,它就会被调用。

编辑:这也不起作用:

.config(function ($compileProvider, routes, $provide) {
    //Lazy define
    $compileProvider.directive('myDirective', function ($rootScope, $location, $filter) {
        console.log( "This IS called" );
        return {
          restrict: 'A',
          link: function (scope, element, attrs) {
              console.log( "This is NEVER called");
            }
        };
    }
}

在指令被惰性加载后,我如何获得运行指令的角度?

在HTML中使用ng-if指令。

  <body ng-app='test'>
    <h1>Hello Plunker!</h1>
    <div my-directive ng-if="defined"></div>
    <button ng-click="defineIt()">Define it</button><br>
  </body>

通过在指令延迟加载后将defined变量设置为trueng-if指令将使用$compile服务编译延迟加载指令。

PLNKR上的DEMO。

相关文章: