AngularJS:ngInclude和动态URL

15

我正在使用 ngInclude 指令加载 HTML 片段。现在我正在寻找传递动态 URL 的最佳方式。我知道我可以使用字符串拼接来创建 URL:

<ng-include src="'/foo/' + fooId + '/bar/' + barId + '/baz/' + bazId"></ng-include>

在我看来,这有点丑陋。

ngHrefngSrc,例如,接受包含{{}}标记的URL。我认为下面的语法更加简洁:

<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
<a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>

有没有更好的方法将动态URL传递给ngInclude?

2个回答

35

不确定这是否会更好,但是您可以在作用域中创建一个函数来封装它。

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


2
回调函数是否必要?为什么不能直接影响 $scope.templateUrl = "/foo/"...? - MaximeBernard
1
回调函数并不是唯一的方法。你可以在作用域上创建一个 templateUrl 属性。你只需要一种一致的方式来更新 fooIdbarIdbazId 的值,就可以达到目的。 - jessegavin
那么,使用回调函数将“自动地”更新templateUrl的值,而直接影响templateUrl则不会? - MaximeBernard
那不正确。你可以用任何一种方法达到相同的结果。我认为在这里使用一个函数更容易。 - jessegavin
@jessegavin 我尝试在暂停后加载页面,但在这种情况下它不起作用,我需要实现的是根据服务器的某些响应来加载页面,因此我创建了一个小暂停来进行测试。$scope.templateUrl = function () { setTimeout(function(){ console.log("5秒后记录日志"); return "app/rsa/summary/summary.html"; }, 5000); } - Min2
在Angular中,我们是否有回调事件可以告诉我们DOM是否已加载,因为模板可能经常更改而DOM也会随之改变。 - graphics123

4

@jessegavin最好使用这段代码

  <ng-include ng-init="tmplUrl = templateUrl();" src="tmplUrl"></ng-include>

如果你将使用这种方式

<ng-include src="templateUrl()"></ng-include>

templateUrl被调用了几次(3次)。尝试使用console.log。我认为是因为$scope变量。

$scope.templateUrl = function() { var url = "/foo/" + $scope.fooId + "/bar/" + $scope.barId + "/baz/" + $scope.bazId; console.log(url); return url; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接