【问题标题】:Why is my $templateCache setup not working with new Angular router?为什么我的 $templateCache 设置不适用于新的 Angular 路由器?
【发布时间】:2015-05-17 02:41:55
【问题描述】:

我不明白为什么我的 $templateCache 设置不起作用...

this plnkr。我将它与new Angular router 一起使用,我在$templateCache 中有我的home 组件模板。 app.js 文件如下所示:

var app = angular.module('app', ['ngNewRouter','app.home']);

app.run(['$templateCache', function($templateCache) {
  $templateCache.put('components/home/home.html', '<h2>The home page</h2>{{home.test}}');
}]);

app.controller('AppController', ['$router','$templateCache', AppController]);

function AppController($router,$templateCache) {
  var vm = this;
  console.log("The template looks like this:",$templateCache.get('components/home/home.html'));
  $router.config([{
    path: '/',
    component: 'home'
  }]);

}

我的 components/home/home.js 文件:

angular.module('app.home', [])
  .controller('HomeController', [HomeController]);

function HomeController() {
  var vm = this;
  vm.test = "String from the home controller";
}

我得到的错误信息是:

http://run.plnkr.co/OFd5k46BCkBdnfkK/components/home/home.html 404 (Not Found)

有什么想法吗?

【问题讨论】:

  • 请注意,您在缓存中将其注册为相对 URL,而不是绝对 URL。
  • 是的,如我所愿。出于某种原因,我应该将其注册为绝对网址吗?

标签: angularjs


【解决方案1】:

我不熟悉ngNewRouter,它似乎在查找模板时使用了一些约定优于配置的方法(我没有看到指定模板 URL 的其他任何地方),但如果你仔细查看错误消息,它说:

加载模板失败:./components/home/home.html(HTTP 状态:404 Not Found)

(注意前面的./)所以,相应地更改缓存键:

$templateCache.put('./components/home/home.html', '<h2>The home page</h2>{{home.test}}');

编辑:

事实上,documentation of ngNewRouter 确实指定了默认(即常规)行为:

默认行为是从./components 删除和提供服务。名为myWidget 的组件使用名为MyWidgetController 的控制器和从./components/my-widget/my-widget.html 加载的模板。

【讨论】:

  • 太棒了!谢谢老兄(或老兄)!谁知道一个小点和一个斜线会对编程产生如此重要的影响:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
相关资源
最近更新 更多