Page 460 - AngularJS权威教程
P. 460
440 第 34 章 下一步
$ npm install --save-dev grunt-angular-templates
这里使用--save-dev任务会将这个Grunt任务存储到package.json文件中,这是
一种很好的做法。保存依赖和版本时可以很容易地为应用程序创建新的开发环
境。如果没有使用package.json文件,可以忽略这个标记,它不会造成任何损害。
npm将会输出一个没有使用package.json的警告信息。
接下来,需要在Gruntfile.js中引用这个新任务,就像这样:
grunt.loadTasks('grunt-angular-templates');
现在,你可以在Grunt任务中安全地使用这个任务了。
34.4.2 用法
这个任务本身会编译一个JavaScript文件,你需要在你的index.html加载它。例如,如果让这
个任务生成templates.js文件,那么就需要在index.html中载入它:
<script src="templates.js"></script>
首先,和任何其他Grunt任务一样,你需要配置它。配置模板的属性是ngtemplates。在这个
ngtemplates配置块内,我们设置了一个子任务,它的名称就是我们加载的Angular模块的名称。
例如:
ngtemplate: {
myApp: {}
}
这个代码生成的templates.js文件输出为:
angular.module('myApp')
.run(['$tempateCache'], function($templateCache) {
$templateCache.put('home.html', ...);
})
子任务的名称myApp与Angular模块的名称相同,$templateCache会将它放到它的模板中。
而选项将会设置在这个子任务内。
34.4.3 可用选项
1. bootstrap
默认情况下,grunt-angular-templates会把function($templateCache) {}包裹到angular.
module('myApp').run(['$templateCache', __]);内。如果你在CommonJS或者RequireJS中使
用了bootstrap选项,那么可以改变这个配置:
// ...
bootstrap: function(module, exports) {
return 'module.exports[module]=' + script + ';';
}