2013-10-17 49 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>