javascript - AngularJS:ui-router href 重写为 ui-sref

标签 javascript angularjs angular-ui-router

我有一个 CMS,它强制页面的 URL 具有特定的模式。我们需要有条件地重写这些链接的 href。

CMS 将在页面上打印如下内容:

<a href="/path/to/the/zoo/gorilla.html">Go</a>

我们的路由器需要实际指向

#/zoo/gorilla

如果我们自己写这个链接,它看起来像:

<a ui-sref="zoo('gorilla')>Go</a>

问题是,我们不能总是保证/zoo/gorilla 部分意味着我们在 zoo('gorilla')。

最简单的方法是将 CMS url 解析为路由器 URL,然后执行如下操作:

link.attr("href", "#/zoo/gorilla");

我理解为什么这通常与 ui-router 的想法背道而驰,但我希望找到一种方法将其用于这种奇怪的情况。

最佳答案

我认为这会起作用,基本上是一个指令,用于在您单击它时更改您前往的 URL。

module.directive('newHref', ['$location',function($location) {
    return function(scope, element, attrs) {
        element.bind('click', newHref);

        function newHref(event) {
            var hrefList = event.target.href.split("/");
            var parent = hrefList[hrefList.length-2];
            var child = hrefList[hrefList.length-1].split(".")[0];

            $location.path("/" + hrefList.slice(0, hrefList.length-2).join("/") + "/" + parent + "/" + child);
        }
    }
}]);

像这样使用它:

<a href="/path/to/the/zoo/gorilla.html" new-href>Go</a>

关于javascript - AngularJS:ui-router href 重写为 ui-sref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655345/

相关文章:

javascript - 使用 Swagger 从 NodeJS 调用 Wordnik API

javascript - Cufon 构建器字体 js 文件在 Fabric.js 中不起作用

Angular 4 构建错误 : Error encountered resolving symbol values statically

AngularJS : multiple resolves in ui. 路由器

javascript - Firefox 首次/页面加载时不会触发 'play' 或 'playing' 事件

javascript - 如何在 Reactjs 组件中使用普通 JavaScript?

javascript - ui bootstrap modal CSS 和打印的问题

AngularJS:限制自定义 contenteditable 指令中的用户输入

javascript - ngRoute 在 Angular 中不起作用?

angularjs - 默认子状态与父状态具有相同的 url