AngularJS: ngInclude and dynamic URLs
Asked Answered
B

2

15

I'm using the ngInclude 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.

ngHref and ngSrc 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?

Brost answered 17/5, 2013 at 19:30 Comment(0)
M
35

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>
</div>

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

Mcginty answered 17/5, 2013 at 19:36 Comment(6)
Is the callback function necessary? Why not affecting directly $scope.templateUrl = "/foo/"... ?Bennett
The callback isn't the only way. You could certainly create a templateUrl property on scope. You would just need a consistent way of updating the value of templateUrl anytime fooId, barId, bazId are changed.Mcginty
So, using a callback will update "automagically" the value of templateUrl whereas affecting directly templateUrl won't?Bennett
That's not correct. You can achieve the same result either way. I think that using a function here is easier.Mcginty
@Mcginty i tried loading page after a pause in that case its not working, what I need to achieve is, load page on basis of certain response from server so i created small pause to give a test. $scope.templateUrl = function () { setTimeout(function(){ console.log("log after 5 seconds"); return "app/rsa/summary/summary.html"; }, 5000); }Sabotage
Do we have a callback event in angular that tells whether the DOM has loaded in this case, as the template might change very often and DOM too.Alanson
H
4

@jessegavin is better use this code

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

if you will use this way

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

templateUrl calls a few times. (3 times). try console.log. i think because of $scope varibles

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

Herefordshire answered 23/8, 2016 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.