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

7
  • Possible duplicate of angularjs directive set template url dynamically - specifically check out the second answer with manipulating ng-include. Commented Apr 20, 2016 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. Commented Apr 20, 2016 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? Commented Apr 20, 2016 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. Commented Apr 20, 2016 at 13:23
  • Ok got it, and the ng-if won't work either? Commented Apr 20, 2016 at 13:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.