我有一个 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/