我可以在字符串中使用Angular ng-href绑定变量吗?

时间:2015-01-22 19:11:43

标签: angularjs angularjs-ng-href

我想将链接href属性绑定到我的控制器中的变量,但我也想将该url绑定到变量。我想使用内置绑定完成此操作,而无需手动监视更改并重新加载URL。这可能吗?

// In the controller
$scope.section = 'section1';
$scope.page = 'page1';
$scope.url = 'http://myurl/{{section}}/{{page}}';


<!-- In the template -->
<a ng-href="{{url}}">Page Link</a>

这是我实际代码的简化。声明模板中的url模式会起作用,但我需要在传入的字符串中定义url。

2 个答案:

答案 0 :(得分:5)

只需设置ng-href

即可
<a ng-href="http://myurl/{{section}}/{{page}}">Page Link</a>

答案 1 :(得分:2)

在控制器中,您不需要使用花括号表达式。

替换它:

$scope.url = 'http://myurl/{{section}}/{{page}}';

有了这个:

$scope.url = 'http://myurl/'+$scope.section+'/'+$scope.page;

要将其绑定在模板中,请使用:

<a ng-href="http://myurl/{{section}}/{{page}}">Page Link</a>

所以,你现在可以留意任何变化。