【问题标题】:Angular Delayed Compilation Skipping ng-bindAngular 延迟编译跳过 ng-bind
【发布时间】:2015-10-14 01:50:38
【问题描述】:

背景

您可以在使用 angular.injector 方法引导您的 Angular 应用程序后调用 $compile

angular.injector(['ng', 'late']).invoke(function($rootScope, $compile) {
    $compile(myElement)($rootScope)
}

这适用于我在 late 模块上创建的指令,但不会调用我的任何 ng-bind

示例

我在一个与我需要编译的元素不同的元素上初始化了 Angular 应用程序。

<div ng-app="test">
</div>

<div id="uncompiled">
{{ $id }}
  <div ng-controller="LateController as cont">
    {{ $id }} {{ "5" }} {{ cont.clicked }}
    <div late-directive="5"></div>
  </div>
</div>

然后,一旦 angular 完成引导,我为应该稍后编译的元素创建模块和指令。

angular.element(document).ready(function() {
  angular.module('late', [])

  angular.module('late').controller('LateController', function($scope) {
    console.log('Make controller', $scope)
    $scope.lateController = true
    this.clicked = 6
  })  

  angular.module('late').directive('lateDirective', function() {
    console.log('Make directive')
    return {
      restrict: 'A',
      template: '<span>INNEREST {{ $id }}</span> COMPILED LATE!!! {{ $id }} {{ cont.clicked }}',
    }
  })

  angular.injector(['ng', 'late']).invoke(function($compile, $rootScope) {
    console.log('Injecting')
    var el = angular.element(document.getElementById('uncompiled'))
    $compile(el)($rootScope)
  })
})

Play around 使用我的代码或查看output

如果您注意到,所有的 {{ }} ng-binds 都不会被替换,而是指令模板 (lateDirective) 被插入到文档中。

问题

为什么有些指令有效而有些无效?

如何让所有指令在延迟的$compile 中正常工作?

【问题讨论】:

    标签: javascript angularjs angularjs-injector


    【解决方案1】:

    通过添加一行简单的 html 来说明为什么会发生这种情况的关键。如果您将另一个元素添加到 LateController

    <input ng-model="cont.text" />
    

    然后整个示例按预期工作。 为什么添加 ng-model 会影响其他指令? 这种行为表明其他指令正在执行;他们只是没有将他们的值输出到屏幕上。

    在一个普通的 Angular 应用程序中,一切都设置好后,应用程序运行一个$digest 循环。但是,当使用$injector.invoke 时,$digest 循环不会自动运行。

    添加 ng-model 时示例运行的原因是 ng-model 运行 $digest

    解决方法:invoke末尾添加$rootScope.$digest()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2015-08-31
      • 1970-01-01
      • 2019-09-03
      • 2021-06-27
      • 2020-07-19
      相关资源
      最近更新 更多