当 Angular.js 应用程序连接 + 缩小以进行分发时,应该如何将 HTML 模板(也称为“部分”)打包在 Angular.js 应用程序中?有没有一种好方法将它们包含在单个文件中,或者我应该压缩包含 main.js
、/templates/*.html
和 的文件夹/styles/app.css
子目录?
Require.js 优化器将所有 JS 文件压缩为适合分发的单个文件 myapp.min.js
,但 HTML 文件仍作为单独文件引用。
作为背景,代码位于 Node.js 服务器中:
public/
/app/main.js
/app/app.js
/app/directives/*.js
/app/filters/*.js
/app/factories/*.js
/app/other/*.js
/app/templates/*.html
运行r.js
后,public/app/**
中的所有文件都有优化的双胞胎,位于不同的目录public/build/**
。但浏览器仍会在其原始位置 /app/templates/*.html
中查找模板。
因此,大概客户端必须将它们放在同一目录中,这似乎是一个不公平的限制。
最佳答案
您必须通过 RequireJS 的 text!
插件来使用模板。例如。对于指令:
define(["text!app/templates/a.html", "myAngularModule"],
function(template, myAngularModule) {
myAngularModule.directive("theDirective", function() {
return {
template: template, // NOTE HERE
...
};
});
});
或者路线:
define(["text!app/templates/a.html", "myAngularModule"],
function(template_a, myAngularModule) {
myAngularModule.config(function($routeProvider) {
$routeProvider.when("some/path", {
template: template_a, // NOTE HERE
...
});
...
});
});
替代方案,使用templateUrl
(以防万一需要):
define(["text!app/templates/a.html", "myAngularModule"],
function(template_a, myAngularModule) {
myAngularModule.config(function($routeProvider) {
$routeProvider.when("some/path", {
templateUrl: "app/templates/a.html", // can be any value actually
...
});
...
});
myAngularModule.run(function($templateCache) {
$templateCache.put(
"app/templates/a.html", // NAME MUST MATCH NAME ABOVE
template_a
);
});
});
关于node.js - 在 Require.js 优化器中打包 *.html 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827912/