AngularJS:ngInclude和动态URL

Mic*_*iss 12 angularjs angularjs-directive angularjs-ng-include

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

<ng-include src="'/foo/' + fooId + '/bar/' + barId + '/baz/' + bazId"></ng-include>
Run Code Online (Sandbox Code Playgroud)

在我眼里,这有点难看.

ngHref并且ngSrc例如,接受包含URL {{}}标记.恕我直言,这种语法更清晰:

<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
<a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
Run Code Online (Sandbox Code Playgroud)

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

jes*_*vin 33

不确定这是否"更好",但您可以在范围上创建一个函数来封装它.

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它......

<div ng-controller="MyCtrl">
  <ng-include src="templateUrl()"></ng-include>
</div>
Run Code Online (Sandbox Code Playgroud)

以下是此类事件的实例:http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p = preview

  • 回调功能是否必要?为什么不直接影响$ scope.templateUrl ="/ foo /"......? (2认同)