如何在Rails应用程序中使用带有Haml模板的AngularJS路由

时间:2013-09-11 22:15:15

标签: javascript ruby-on-rails angularjs ruby-on-rails-4

我有app / assets / templates / api-list.haml我想用作AngularJS模板。我跟着this tutorial创建了一个templates.js文件,它将我编译的所有Haml AngularJS模板插入$templateCache。但是,我似乎无法使这些缓存的模板与我的AngularJS路由一起使用:

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

当我加载我的应用时,我在浏览器控制台中看到404错误,因为它尝试向http://localhost:3000/api-list发出请求。我可以在浏览器中查看/assets/templates.js并看到$templateCache.put("api-list"已定义,因此应该有一个名为“api-list”的模板。我在定义路由之前在我的页面中加载templates.js。

我也尝试在我的路由配置中注入$templateCache,如下所示:

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

但这会导致Uncaught TypeError: Cannot call method 'get' of undefined from ApiApp错误。如果我将第一行更改为api_app.config(['$routeProvider', '$templateCache', ($routeProvider, $templateCache) ->,则会收到错误Uncaught Error: Unknown provider: $templateCache from ApiApp

如何说服我的路线使用$templateCache中的模板,而不是尝试通过新请求加载?

2 个答案:

答案 0 :(得分:9)

我在没有$templateCache的情况下工作了。我使用以下命令创建了config / initializers / haml.rb文件:

Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate

然后在我的config / application.rb中,我添加了config.assets.paths << Rails.root.join('app', 'assets', 'templates')

我还将模板文件从api-list.haml重命名为api-list.html.haml。我的路线现在看起来像这样:

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

我不喜欢在其中使用/assets硬编码,因此我可能最终将此文件从routes.js.coffee更改为routes.js.erb并使用Rails帮助程序获取路径。< / p>

答案 1 :(得分:3)

您遇到templateCache问题的原因是路由在配置块中。如果您参考有关modules的AngularJS文档,您将看到以下行:

  

只能将提供程序和常量注入配置块。这是为了防止服务在完全配置之前意外实例化。