【问题标题】:Rails 4 + AngularJS: templateUrl for directive not found?Rails 4 + AngularJS:找不到指令的templateUrl?
【发布时间】:2014-07-31 15:31:34
【问题描述】:

我正在尝试在 AngularJS 中创建一个指令来将我的 HTML 拆分为可重用的部分:

app/assets/javascripts/products/directives/products.js:

app.directive('productsfilter', function() {
  return {
    restrict: 'E',
    templateUrl: "/templates/filter-template.html"
  }
});

但是,没有找到模板:

Error: [$compile:tpload] Failed to load template: /templates/filter-template.html http://errors.angularjs.org/1.2.20/$compile/tpload?p0=%2Ftemplates%2Ffilter-template.html

我也尝试了../templates/filter-template.htmltemplates/filter-template.html,但都没有成功。是因为 Rails 的资产管道吗?

这是我在 app/assets/javascripts 中的文件夹树:

└── products
    ├── controllers
    │   ├── mens_controller.js
    │   ├── productscontroller.js
    │   ├── womens_eyeglasses_controller.js
    │   └── womens_sunglasses_controller.js
    ├── directives
    │   └── products.js
    ├── filters
    │   └── productsfilters.js
    ├── services
    │   └── productsservices.js
    └── templates
        └── filter-template.html

【问题讨论】:

  • 检索另一个 javascript 文件的 url 是什么? templateUrl 应该是相对于它们的。
  • 也许是因为我使用的是 Rails 路由而不是 Angular 路由?看起来 Rails 正在公共文件夹中查找文件:GET http://localhost:3000/templates/filter-template.html 404 Not Found
  • 是的,它正在公用文件夹中查找。网址应该比这更长。可能是 assets/javascripts/products/templates/filter-template.html 或更短/更长。
  • 我决定将我的 templates.html 文件放到 public/templates 中。之后它工作了
  • 我为此绞尽脑汁一个小时,我所要做的就是重新启动 Rails 服务器

标签: ruby-on-rails angularjs


【解决方案1】:

我也遇到过同样的问题。我的模板路径是:

assets/templates/partials/question/multipleChoice.html

当我将模板移入时:

资产/模板/multipleChoice.html
嵌入的:
 工作。也许,深入挖掘是 
asset_path()
方法的局限性。

为了让方法能够找到模板,我指出来了,像这样:

templateUrl: ""
并且成功了。 (当然,您必须将扩展名更改为 .js.erb)。

我不想将我的模板放在公用文件夹中。我希望 Rails 为我处理它并使其动态化。

【讨论】:

    【解决方案2】:
    app.directive('productsfilter', function() {
      return {
        restrict: 'E',
        templateUrl: "filter-template.html"
      }
    });
    

    如果你不使用它,请使用它。

    gem 'angular-rails-templates'
    

    为我工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      相关资源
      最近更新 更多