![](/img/trans.png)
[英]AngularJs ui-router ui-sref not generating href from nested state with parameter
[英]AngularJS: ui-router href rewrite into ui-sref
我有一個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>
看起來好像進入了危險區域,但是您可以創建“ href”指令,該指令將自動替換href
屬性的值。 不需要額外的屬性,但這可能會使您的代碼有點含糊不清...
module
.directive('href', function() {
return function(scope, element, attrs) {
var ngUrl; // convert CMS url to Angular URL somehow
if(attrs.href === '/path/to/the/zoo/gorilla.html') {
ngUrl = '#/zoo/gorilla';
}
element[0].href = ngUrl;
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.