2

I know that there's a similar question on Stack Overflow but it's not quite what I am looking for. The ng-include alows me to dynamically change the path but then I can't access scope variables.

Basically I would like to dynamically assign a template URL to a directive through an AJAX call. Unfortunately I can't seem to bind the directive attribute to an actual scope variable.

app.directive('appsdirective', function() {
    return {
        templateUrl : function(elem,attrs) {
            // attrs.templateUrl contains "app.appPath" rather than the content itself
            return attrs.templateUrl;
        },
        restrict : 'EA',
        scope : false
    }
});

<appsdirective template-url="{{app.appPath}}"></appsdirective>

$scope.app is a main controller variable that is undefined at the beginning but gets initialized later through an AJAX request. I also tried manually initializing the variable but it didn't help and I get this obvious error in the console:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/%7B%7Bapp.appPath%7D%7D

Community
  • 1
  • 1
raz3r
  • 3,071
  • 8
  • 44
  • 66
  • Possible duplicate of [angularjs directive set template url dynamically](http://stackoverflow.com/questions/26397424/angularjs-directive-set-template-url-dynamically) - specifically check out the second answer with manipulating ng-include. – ajmajmajma Apr 20 '16 at 13:16
  • The second answer uses ng-include which I am trying to avoid. The first one uses the templateUrl function but it doesn't seem to work in the current version of AngularJS. – raz3r Apr 20 '16 at 13:19
  • What exactly do you mean by I can't access the scope vars though? Also will using the ng-if to not render until you have the ajax call back not work either? – ajmajmajma Apr 20 '16 at 13:20
  • Inside the directive I am accessing lots of parent controller variables but when I use the ng-include solution the binding stops working. – raz3r Apr 20 '16 at 13:23
  • Ok got it, and the ng-if won't work either? – ajmajmajma Apr 20 '16 at 13:32
  • The ng-if looks outdated from the comment but I may be wrong. Btw to be more precise with the ng-include solution I can't access directive scope from the parent scope (basically ng-model doesn't work anymore in the directive). – raz3r Apr 20 '16 at 13:39
  • give the ng-if a shot before you rule it out :) – ajmajmajma Apr 20 '16 at 19:54

0 Answers0