【问题标题】:AngularJS: ngInclude and dynamic URLsAngularJS:ngInclude 和动态 URL
【发布时间】:2026-01-14 15:20:06
【问题描述】:

我正在使用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?​​p>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-include


    【解决方案1】:

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

    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

    【讨论】:

    • 回调函数有必要吗?为什么不直接影响 $scope.templateUrl = "/foo/"... ?
    • 回调不是唯一的方法。您当然可以在作用域上创建 templateUrl 属性。您只需要在 fooIdbarIdbazId 发生更改时随时更新 templateUrl 的值。
    • 那么,使用回调将“自动”更新 templateUrl 的值,而直接影响 templateUrl 不会?
    • 这不正确。无论哪种方式,您都可以获得相同的结果。我认为在这里使用函数更容易。
    • @jessegavin 我尝试在暂停后加载页面,在这种情况下它不起作用,我需要实现的是,根据服务器的某些响应加载页面,所以我创建了一个小暂停来进行测试。 $scope.templateUrl = function () { setTimeout(function(){ console.log("5 秒后的日志"); return "app/rsa/summary/summary.html"; }, 5000); }
    【解决方案2】:

    @jessegavin 最好使用此代码

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

    如果你会使用这种方式

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

    templateUrl 调用了几次。 (3次)。尝试控制台.log。我认为是因为 $scope 变量

    $scope.templateUrl = function() { var url = "/foo/"+ $scope.fooId +"/bar/"+ $scope.barId +"/baz/"+ $scope.bazId; 控制台.log(url); 返回网址; }

    【讨论】: