【问题标题】:AngularJS: ng-if plus ng-include throws TypeError: Cannot call method 'insertBefore' of nullAngularJS:ng-if 加上 ng-include 抛出 TypeError:无法调用 null 的方法“insertBefore”
【发布时间】:2026-01-10 03:50:01
【问题描述】:

我正在使用Ionic Framework(版本v1.0.0-beta.11)编写一个应用程序,但我相信这个问题与底层的AngularJS(版本v1.2.17)相当相关。

在同一元素中同时使用ng-ifng-include 时遇到问题。当模型中ng-if 的条件发生变化时,出现以下错误(在 Chrome 和 Android 中测试):

TypeError: Cannot call method 'insertBefore' of null
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:10843:14
    at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:8187:18)
    at forEach.after (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10842:5)
    at Object.JQLite.(anonymous function) [as after] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10913:17)
    at Object.enter (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12015:17)
    at Object.enter (http://localhost:8100/lib/ionic/js/ionic.bundle.js:30107:21)
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:27441:26
    at publicLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:13779:29)
    at boundTranscludeFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:13894:21)
    at controllersBoundTransclude (http://localhost:8100/lib/ionic/js/ionic.bundle.js:14492:18) 


我已经在一个基于 Ionic 入门项目 (ionic start [PATH] tabs) 的简单项目中隔离了这个问题。这是代码:http://plnkr.co/edit/CczR5NgFLqR143jQJ08C?p=preview

我挖掘了错误,发现抛出错误的函数是after: function(element, newElement) {...
打印出传递给函数的参数,element[object Comment],内容为 <!-- ngInclude: -->newElement[[object HTMLDivElement]]

我读到 here 说,自 Angular 1.2.2 起,ng-ifng-include 两个指令都可以组合使用。

有人遇到过这个问题吗?是否有任何已知的修复方法(除了将ng-if 移动到父元素)?

提前致谢,
  拉法。

【问题讨论】:

    标签: angularjs ionic-framework


    【解决方案1】:

    ng-ifng-include 都排队等待执行,ng-if 具有更高的优先级,因此它首先运行。如果表达式为假,则ng-if 删除元素,但不会取消ng-include 的运行。由于元素被移除,ng-include 无法将加载的内容注入到元素中,您会收到此错误。

    您可以考虑在ng-include 中添加一个表达式并删除ng-if。如果表达式返回一个空字符串,ng-include 将不会尝试加载任何内容。

    分叉你的 plunkr 并在 2 秒后加载内容:http://plnkr.co/edit/oTnJ0bTlMBD7yrUmPloq?p=preview

    标记

    <ng-include src="source"></ng-include>
    

    控制器

    // In the controller, check
    $timeout(function () {
      $scope.source = 'templates/Nocontent.html';
    }, 2000);
    

    【讨论】:

    • 仅作记录,如果条件是模型中的不同变量,"&lt;div ng-include src="!content ? 'templates/mytemplate.html' : null"&gt;&lt;/div&gt; 工作正常。
    • 另请注意,即使ng-include 条件为假时未附加div 元素,也会调用任何关联的控制器(使用ng-controller)。
    • 实际上调用了控制器但$scope是空的
    • 如果将ng-controller 与条件ng-include 一起使用,请注意控制器将只运行一次:*.com/a/26006589/2050333
    最近更新 更多