I have app/assets/templates/api-list.haml that I want to use as an AngularJS template. I followed this tutorial to create a templates.js file that inserts all my compiled Haml AngularJS templates into $templateCache
. However, I can't seem to make these cached templates work with my AngularJS routes:
api_app.config(['$routeProvider', ($routeProvider) ->
$routeProvider.when '/',
templateUrl: 'api-list'
controller: api_app.ApiListController
$routeProvider.otherwise
redirectTo: '/'
])
When I load my app, I see a 404 error in the browser console because it tried to do a request to http://localhost:3000/api-list
. I can look at /assets/templates.js in the browser and see that $templateCache.put("api-list"
is defined, so there should be a template called "api-list". I am loading templates.js in my page before defining routes.
I also tried injecting $templateCache
in my route config like so:
api_app.config(['$routeProvider', ($routeProvider, $templateCache) ->
$routeProvider.when '/',
template: $templateCache.get('api-list')
controller: api_app.ApiListController
$routeProvider.otherwise
redirectTo: '/'
])
This causes an Uncaught TypeError: Cannot call method 'get' of undefined from ApiApp
error though. If I change the first line to api_app.config(['$routeProvider', '$templateCache', ($routeProvider, $templateCache) ->
, I instead get the error Uncaught Error: Unknown provider: $templateCache from ApiApp
.
How can I convince my routes to use the template from $templateCache
instead of trying to load it via a new request?
I got something working without $templateCache
. I made a config/initializers/haml.rb file with the following:
Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate
Then in my config/application.rb, I added config.assets.paths << Rails.root.join('app', 'assets', 'templates')
.
I also renamed my template file from api-list.haml
to api-list.html.haml
. My routes look like this now:
api_app.config(['$routeProvider', ($routeProvider) ->
$routeProvider.when '/',
templateUrl: '/assets/api-list.html'
controller: api_app.ApiListController
$routeProvider.otherwise
redirectTo: '/'
])
I don't like having /assets
hard-coded in there, so I may end up changing this file from routes.js.coffee to routes.js.erb and using Rails helpers to get a path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With