Michael Weiss Michael Weiss - 2 months ago 10x
AngularJS Question

AngularJS: ngInclude and dynamic URLs

I'm using the

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.

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>

Here's a live example of this type of thing: http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=preview