问题描述
我使用了 ngInclude
指令来加载HTML片段。现在我正在寻找通过一个动态URL的最佳方式。我知道我可以创建一个字符串连接的网址:
< NG-包括SRC =/富/+ fooId +'/酒吧/'+ barId +' /巴兹/'+ bazId>< / NG-包括>
在我眼里,这是一个有点难看。
ngHref
和 ngSrc
例如,接受包含网址 {{}}
标记。恕我直言,这种语法干净多了:
< IMG NG-SRC =/富/ {{fooId}} /酒吧/ {{barId}} /巴兹/ {{bazId}}/>
<一个NG-HREF =/富/ {{fooId}} /酒吧/ {{barId}} /巴兹/ {{bazId}}/>
有没有更好的方式来传递动态URL到ngInclude? P>
不知道这是更好或没有,但你可以在你的范围内创建一个函数来封装这一点。
app.controller(MyCtrl功能($范围){
$ scope.fooId =123;
$ scope.barId =ABC;
$ scope.bazId =ABC; $ scope.templateUrl =功能(){
回归/富/+ $ scope.fooId +/酒吧/+ $ scope.barId +/巴兹/+ $ scope.bazId;
}
});
然后你会使用它像这样...
< DIV NG控制器=MyCtrl>
< NG-包括SRC =templateUrl()>< / NG-包括>
< / DIV>
下面是这种类型的事情的一个活生生的例子:<一href=\"http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=$p$pview\">http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=$p$pview
I'm using the ngInclude
directive to load HTML fragments. Now I'm looking for the best way to pass a dynamic URL. I know I can create the URL with string concatenation:
<ng-include src="'/foo/' + fooId + '/bar/' + barId + '/baz/' + bazId"></ng-include>
In my eyes this is a bit ugly.
ngHref
and ngSrc
for example, accept URLs containing {{}}
markup. IMHO this syntax is much cleaner:
<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
<a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
Is there a better way to pass dynamic URLs to ngInclude?
Not sure if this is "better" or not, but you could create a function on your scope to encapsulate this.
app.controller("MyCtrl", function($scope) {
$scope.fooId = "123";
$scope.barId = "abc";
$scope.bazId = "abc";
$scope.templateUrl = function() {
return "/foo/"+ $scope.fooId +"/bar/"+ $scope.barId +"/baz/"+ $scope.bazId;
}
});
Then you would use it like so...
<div ng-controller="MyCtrl">
<ng-include src="templateUrl()"></ng-include>
</div>
Here's a live example of this type of thing: http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=preview
这篇关于AngularJS:ngInclude和动态网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!