【问题标题】:Loading AngularJS combined directive templates with NgInclude使用 NgInclude 加载 AngularJS 组合指令模板
【发布时间】:2015-02-14 23:36:17
【问题描述】:

我想将我的所有指令模板包含在一个文件中,以减少加载指令繁重页面所需的 HTTP 请求数。

我有这个指令

angular.module('bwDirectives', [])
    .directive('bwInfoCard', function () {
        return {
            restrict: 'E',
            transclude: false,
            replace: true,
            scope: { title: '=' },
            templateUrl: "one-template",
        };
    })

如果我像这样指定内联模板,那么它会正确加载指令模板:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Directive Test Fixture</title>
    <link rel="stylesheet" href="../Style.css" type="text/css" />
    <script src="../../../Libraries/angular.min.js"></script>
    <script src="../Widget.js"></script>
    <script src="./Fixture.js"></script>
</head>
<body ng-app="BaseWidgetFixtures">
    <h1>Base Info Card</h1>
    <script type="text/ng-template" id="one-template">
        <div>This is first template</div>
    </script>
    <script type="text/ng-template" id="two-template">
        <div>This is second template</div>
    </script>
    <div ng-controller="InfoCardFixture">
        <bw-info-card title="title"></bw-info-card>
    </div>
</body>
</html>

如果我尝试通过 NgInclude 包含模板,它会失败。我猜它会在执行 NgInclude 之前尝试为指令加载模板(即使它在文件中较早)。页面中包含了正确的脚本标签。

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Directive Test Fixture</title>
    <link rel="stylesheet" href="../Style.css" type="text/css" />
    <script src="../../../Libraries/angular.min.js"></script>
    <script src="../Widget.js"></script>
    <script src="./Fixture.js"></script>
</head>
<body ng-app="BaseWidgetFixtures">
    <h1>Base Info Card</h1>
    <div ng-include src="'templates.html'"></div>
    <div ng-controller="InfoCardFixture">
        <bw-info-card title="title"></bw-info-card>
    </div>
</body>
</html>

是否有我遗漏的东西,或者您不能使用 NgInclude 模板与指令一起使用?

谢谢。

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive


    【解决方案1】:

    看看这个讨论皮特培根达尔文解释指令链接/编译的顺序。 https://groups.google.com/forum/#!topic/angular/3HsNz4ncnYA/discussion。您可能可以重新排列您的 html 以使其正常工作,但这并不是 ng-include 的真正目的。如果您不想使用 AJAX 加载模板,我建议您使用 angular-templatecache 之类的东西。

    【讨论】:

    • 有没有办法不用 grunt/gulp?我不想运行一个监听器。我认为我不介意手动将它们放入一个文件中,只要我仍然可以轻松地将其包含到页面中。
    • 我看到了这个github.com/astik/angular-combine,但在没有以前的凉亭经验的情况下,我很难让它工作。我希望有一些更简单的东西,比如一个 JS 文件。
    • 好吧,我想我明白了。我只需要 bower 来下载最新版本,然后可以将 angular-combine.min.js 链接到页面。现在我只是让所有模板都来自缓存(所以正则表达式是.*)我不确定这是否是预期的使用模式。
    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多