【问题标题】:AngularJS: Directive templates loading regardless of ng-if conditionAngularJS:无论 ng-if 条件如何,都加载指令模板
【发布时间】:2013-11-06 00:26:40
【问题描述】:

我正在使用指令将我的代码分成模板,并且我希望这些模板根据 if 条件加载。现在,当我查看网络流量时,无论是否满足 ng-if 条件,Angular 都会将所有模板发送到客户端。

<div class="container">
    <ul>
        <template1 ng-if="taskCategory == 'condition1'"></template1>
        <template2 ng-if="taskCategory == 'condition2'"></template2>
        <template3 ng-if="taskCategory == 'condition3'"></template3>
    </ul>
</div>

这是我的指令模板之一的示例:

/* Directive Template */
.directive('template1', [function() {
    return {
        restrict: 'E',
        templateUrl: 'view/templates/template1.tpl.html'
    };
}])

这是预期的行为吗?它在视觉上按预期工作。但我的印象是ng-if 数据会根据条件延迟加载。还是我误会了ng-if的用法?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    这绝对是预期的行为。 ng-if 将根据条件有条件地从 DOM 中删除元素。元素在被移除之前仍会被渲染(否则元素的克隆会被添加回 DOM)。

    AngularJS: ngif 文档的第一段中说明了该行为。

    【讨论】:

    • 如果 ng-if 最初解析为 false,假设是 ng-repeat,DOM 是否已构建(第一次)?
    • DOM 在ng-if 移除元素之前构建。
    • 该文件说该元素在 ng-if 处理它之前被编译。这也意味着它也必须编译指令。
    • 这是 Angular 1.5 开箱即用的功能;)
    【解决方案2】:

    'view/templates/template1.tpl.html' 将在使用template1 指令的第一个视图的编译/链接阶段加载。

    html 响应(此阶段仅是文本)将缓存在 $templateCache 中(默认情况下,Angular 会这样做)并且在整个页面刷新之前永远不会有第二个 ajax。

    即使在这种情况下,下一个 ajax 调用也会从浏览器缓存中提供,您可能只会看到 304 Not Modified。由于 html 是静态文件,因此应为它们提供适当的缓存选项(例如 ETag 标头),并确保在更改代码时重新加载它们(不要求用户清除其临时文件)。

    【讨论】:

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