我使用ngInclude
指令加载HTML片段。现在我正在寻找传递动态URL的最佳方法。我知道我可以用字符串连接创建URL:
<ng-include src="'/foo/' + fooId + '/bar/' + barId + '/baz/' + bazId"></ng-include>
在我看来这有点丑。
以 ngHref
和ngSrc
为例,接受包含{{}}
标记的url。恕我直言,这个语法要干净得多:
<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
<a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
是否有更好的方法来传递动态url给ngInclude?
不确定这是否"更好",但您可以在作用域上创建一个函数来封装它。
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;
}
});
那么你可以这样使用…
<div ng-controller="MyCtrl">
<ng-include src="templateUrl()"></ng-include>
</div>
下面是这类事情的一个实例:http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=preview
@jessegavin最好使用这段代码
<ng-include ng-init="tmplUrl = templateUrl();" src="tmplUrl"></ng-include>
如果你想这样使用
<ng-include src="templateUrl()"></ng-include>
templateUrl调用几次。(3次)。console.log试试。我想是因为$scope变量
美元范围。templateUrl = function() {Var url = "/foo/"+ $scope。fooId +"/bar/"+ $scope。barId +"/baz/"+ $scope.bazId;console.log (url);返回的url;}