How to use AngularJS routes with Haml templates in a Rails application

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 of my compiled Haml AngularJS $templateCache into $templateCache . However, I cannot get these cached patterns to work with my AngularJS routes:

 api_app.config(['$routeProvider', ($routeProvider) -> $routeProvider.when '/', templateUrl: 'api-list' controller: api_app.ApiListController $routeProvider.otherwise redirectTo: '/' ]) 

When I download my application, I see a 404 error in the browser console because it tried to execute the request http://localhost:3000/api-list . I can look at /assets/templates.js in a browser and see that $templateCache.put("api-list" defined, so there should be a template called "api-list". I load templates.js on my page before defining the routes .

I also tried injecting $templateCache into my route configuration like this:

 api_app.config(['$routeProvider', ($routeProvider, $templateCache) -> $routeProvider.when '/', template: $templateCache.get('api-list') controller: api_app.ApiListController $routeProvider.otherwise redirectTo: '/' ]) 

This results in an Uncaught TypeError: Cannot call method 'get' of undefined from ApiApp . If I change the first line to api_app.config(['$routeProvider', '$templateCache', ($routeProvider, $templateCache) -> , we get the Uncaught Error: Unknown provider: $templateCache from ApiApp .

How can I convince my routes to use the template from $templateCache instead of loading it with a new request?

+4
source share
2 answers

Something works for me without $templateCache . I created 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 are as follows:

 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 there, so I can eventually change this file from route.js.coffee to routes.js.erb and get the path using Rails helpers.

+9
source

The reason you are having problems with templateCache is because the routes are in the configuration block. If you are referring to AngularJS documentation on modules , you will see the following line:

Only suppliers and constants can be entered into configuration blocks. This is to prevent accidental creation of services before they are fully configured.

+3
source

Source: https://habr.com/ru/post/1501743/


All Articles