2

I am trying to make an angular directive that renders dynamic content urls based on an attribute placed on the directive. Example:

Directive:

angular
    .module('myModule')
    .directive('myContent', directive);

function directive() {
    return {
        replace: true,
        templateUrl: function (elem, attrs) {
            return attrs.contentUrl;
        }
    };
}

HTML:

<div my-content content-url="url/to/my-content.html"></div>

However what I would like is for the content-url attribute to be populated by a string from the controller. So let's say the controller is using the "controllerAs" syntax with the name "home", I would like the html to read:

<div my-content content-url="{{home.myContent.url}}"></div>

However within the directive's templateUrl function, the contentUrl attribute is being sent literally as "{{home.myContent.url}}". How can I get this value to evaluate before running the templateUrl function? Or, is there a better way to have simple, dynamic content available from a directive?

2
  • Should be possible by addingscope: { conentUrl: '=' } to your directive function, and leave out the curly brackets when using the it in your html. Then you need to $watch the value of $scope.contentUrl in the directive. Alternatively you should also be able to use $attr.$observe in link function of the directive, though I don't have much experience with that. Google is you friend :-) Commented Nov 16, 2016 at 13:45
  • 2
    Sounds like you're trying to recreate what angular already does natively with ng-include. Unless you're trying to recreate it for learning purposes, I'd just use ng-include. Otherwise, might not be a bad idea to check out the source code to see how they do it. Commented Nov 16, 2016 at 15:03

1 Answer 1

0

The answer is provided by @crhistian-ramirez:

Just use ng-include

<div ng-include="vm.myContent.url"></div>
Sign up to request clarification or add additional context in comments.

Comments

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.