javascript - 如何配置 Angular 以使用没有尾部斜杠的基本路由?

标签 javascript angularjs

期望的行为

我有一个位于此 URL 的搜索页面:

http://example.com/search

所需的行为是将提供的查询参数传递给页面,并在用户键入不同的查询时进行更新。

例如,

http://example.com/search?q=foo

在页面加载时在包含“foo”的搜索框中产生结果。如果用户在搜索框中输入“delicious pancakes”,地址栏的 URL 将自动更新为:

http://example.com/search?q=delicious+pancakes

这部分工作正常;我正在使用 $watch监视查询的值,然后通过 $location.search('q', newValue) 更新地址栏.

但我想使用 HTML5 模式(我正在使用 $locationProvider.html5Mode(true) ),并且我需要 hashbang 回退才能为 IE9 用户工作。

我希望 hashbang 后备看起来像这样:

http://example.com/search#?q=delicious+pancakes

问题

如果我不设置 <base>元素,$location 服务将域之后的所有内容都视为路径,因此在 IE9 中它实际上回退到这个:

http://example.com/#search?q=delicious+pancakes

这导致浏览器重定向到主页(即,它使我完全离开搜索页面!)

所以最好的做法似乎是使用 <base>标签;所以我把它设置为

<base href="http://example.com/search/"></base>

(注意尾部的斜杠;我知道 Angular 和 HTML 规范都要求这样做。)

但是,这意味着我必须使用以下 URL:

http://example.com/search/?q=delicious+pancakes

(IE9 回退为 http://example.com/search/#?q=delicious+pancakes)

这行得通,但我不想要求用户在“搜索”之后和问号之前键入斜线。目前,如果我尝试通过 http://example.com/search?q=foo 访问该页面,我在控制台中收到此错误:

TypeError: whole is undefined

这个错误显然是由 $location 服务的 $$rewrite 引起的函数不返回任何东西。作为引用,我将从 angular.js 复制源代码:

this.$$rewrite = function(url) {
    var appUrl, prevAppUrl;

    if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
      prevAppUrl = appUrl;
      if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
        return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
      } else {
        return appBase + prevAppUrl;
      }
    } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
      return appBaseNoFile + appUrl;
    } else if (appBaseNoFile == url + '/') {
      return appBaseNoFile;
}

有什么方法可以在“搜索”后没有斜杠的情况下实现所需的行为,并且仍然支持 IE9?

最佳答案

使用条件语句从 HTML5 模式中排除 IE9:

if(!!$window.innerWidth && !$window.matchMedia)
  {
  $locationProvider.html5Mode({enabled: false, requireBase: false});
  $locationProvider.hashPrefix("search");
  }
else
  $locationProvider.html5Mode({enabled: true, requireBase: false});

引用资料

关于javascript - 如何配置 Angular 以使用没有尾部斜杠的基本路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24690748/

相关文章:

javascript - 我什么时候需要检查 origin 属性?

javascript - 如何根据总和限制数字输入

javascript - 在 Angular js 中使用电池管理器

javascript - Angular 翻译指令中的 XSS

javascript - 添加动态输入字段,从数组中分配新的 id

javascript - Angular - 仅当您单击 div 的特定区域时,div 上的 ng-click 才有效

javascript - 从列表 JQUERY 中获取点击输入的正确名称

javascript - Angularjs ng 单击清除输入并更新范围

javascript - Angular Directive(指令) : switch between two templates dynamically

javascript - $index 不存在于 ng-repeat 中 - 答案在我原来的帖子中