2013-10-17 226 views
0

如果我想爲一個元素添加一個動態創建的ng-href,我該如何讓它像通常的ng-href一樣工作?動態添加ng元素

<a test-href="/link">Test link</a> 

指令:

app.directive("testHref", function() { 
    return { 
    link: function(scope, elem, attr) { 
     var newlink = attr.dbHref + "/additional/parameters"; 
     attr.$set("ng-href", newlink); 
    } 
    }; 
}); 

這將產生<a test-href="/link" ng-href="/link/additional/parameters">Test link</a>,但我怎麼也得到了NG-HREF的行爲,因爲它應該?

+0

爲什麼?你爲什麼想這樣做? – ganaraj

+0

爲頁面上的所有鏈接添加附加參數 – WhoDidThis

回答

2

http://jsfiddle.net/UnpSH/

app.directive("testHref", function($compile) { 
    return { 
    link: function(scope, elem, attr) { 
     var newlink = attr.dbHref + "/additional/parameters"; 
     attr.$set("ng-href", newlink); 
     elem.removeAttr('test-href'); // prevent recursion 
     $compile(elem)(scope); // compile it again 
    } 
    }; 
}); 

不知道你想要什麼來實現的,但你應該使用類似ng-href = "/path/{{scopeVariable}}"動態改變你的鏈接。

+0

Sweet,這是從不刪除使我獲得的'test-href'屬性的遞歸。 – WhoDidThis

0

我不認爲你需要編寫一個自定義指令有一個動態的網址爲href。您可以使用ng-href和範圍參數綁定。

<a ng-href="/path/{{dynamic_var_on_scope}}/123/?p={{var2}}"> Click Here </a> 
+0

我該如何在我的控制器中獲得p參數? –

+0

您需要將參數添加到$ scope。您可以將$ scope注入到控制器。 – erandac

0

如果你想一個動態的URL綁定href那麼你可以操縱你的網址在ng-clickng-mousedown事件並綁定到目標元素。

JS:

var goToDetailPage = function (event, id) { 
    var newState = $state.href('DetailView', {id: id}); 
    jQuery(event.target).attr('href',newState); 
}; 

HTML:

<a ng-mousedown="goToDetailPage($event, id)"> Click Here </a>