Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocknrollMarc/2949bcde580e90b336a6 to your computer and use it in GitHub Desktop.
Save rocknrollMarc/2949bcde580e90b336a6 to your computer and use it in GitHub Desktop.

AngularJS + Rails Asset Pipeline

This is my hand-rolled solution for getting Angular assets (Controllers, Models, Directives, Templates, etc.) integrated into the Rails Asset Pipeline.

Templates and the $templateCache

Of particular note: this hack will also load the AngularJS $templateCache with your templates, while allowing you to use Slim, ERB, etc. to write your templates.

//= require angular
//= require angular-animate
//= require angular-resource
//
//= require ./my_app/bootstrap
//= require ./my_app/templates
//= require_tree ./my_app/controllers
//= require_tree ./my_app/directives
//= require_tree ./my_app/models
# app/assets/javascript/my_app/bootstrap.js.coffee
@myApp = angular.module('myApp', ['ngResource', 'templates'])
# config/initializers/slim_assets.rb
Rails.application.assets.register_engine('.slim', Slim::Template)
<%# app/assets/javascript/my_app/templates %>
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 ** *})
Dir.glob(templates).each do |f|
depend_on(f)
key = f.gsub(%r(^#{app_root}/templates/),'').split('.').first
content = environment.find_asset(f).body
%>
$templateCache.put("<%= key %>", "<%= escape_javascript(content) %>" );
<% end %>
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment