我计划将我当前的应用程序转换为 Angular 应用程序。我以前从未有机会使用 Angular 和 Rails 一起工作。我计划在 Rails 应用程序中逐个功能地实现 Angular。但我仍然担心文件夹结构。
对于在 Rails 应用程序中保存 Angular 文件的位置有任何约定吗?
Angular 也是这种开发的良好候选者(逐个功能)还是我应该研究其他技术?
最佳答案
FDD(逐个功能开发)与 MVC 框架配合良好,Angular 就是其中之一。
通常建议将 JS 文件(任何 JS 文件,而不仅仅是 Angular)存储在 app/assets/javascripts
中,以便 Rails Assets 管道自动获取它们。除此之外没有任何约定,将它们存储在您认为有意义的任何结构中。
我说的是一般情况,因为如果你的 Angular 代码变得很大,你最好将其从 app
文件夹中提取出来。然后,您必须配置 Assets 管道以使用您的新结构。
对于小型项目,我喜欢将 Angular javascript 文件保存在 app/assets/javascripts/angular
app/assets/javascripts/angular
/controllers/
/directives/
/helpers/
/models/
/services/
apps.js
templates.js.erb
View 位于app/assets/templates
中。
我遇到的一个大障碍是让 Angular View 与 Rails 的 Assets 管道配合使用。在开发中,您不会注意到任何事情,但是一旦在生产中部署,并且 Assets 管道启动,Angular 就无法再找到 View 了。
为了使资源管道为 AngularJS View 提供服务,我必须创建一个模板缓存。
// templates.js.erb
(function(){
'use strict';
// version 0.01
// increase this every-time you deploy to production
angular.module('templates', []).run(['$templateCache', function($templateCache) {
<%
environment.context_class.instance_eval { include ActionView::Helpers::JavaScriptHelper }
app_root = File.expand_path('../../../', __FILE__)
templates = File.join(app_root, %w{templates ** *.html})
Dir.glob(templates).each do |f|
key = f.gsub(%r(^#{app_root}/templates/), '')
html = File.read(f).squish
%>
$templateCache.put("<%= key %>", "<%= escape_javascript(html) %>");
<% end %>
}]);
}());
然后您必须在模块中注入(inject)模板
angular.module("myModule", ['templates']);
关于javascript - 在 Rails 中存储 Angular 文件的最佳位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693036/