1

I have simple directive like this :

app.directive('sample',function(){
 return{
           restrict:'E',
    template:'<a href="#">Hello sample</a>',
    templateUrl:''
 }
});

i want when user declare templateUrl in tag like this :

<sample template="some url"></sample>

use templateUrl but if nothing set use default template in directive

2 Answers 2

2

template and templateUrl can be specified as functions taking two arguments - tElement and tAttrs.

An easy way is to move your default template and perform your logic in the templateUrl function:

app.directive("sample", [
  function() {

    var defaultTemplate = 'default.html';

    return {
      restrict: 'E',
      templateUrl: function (tElement, tAttrs) {
        return tAttrs.template || defaultTemplate;
      }
    }
  }
]);

Demo: http://plnkr.co/edit/rrPicuzzb6YF4Z6yh3Rn?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

I suggest using transclude:

app.directive('sample',function(){
    return {
       restrict:'E',
       transclude: true,
       template:'<a href="#">Hello sample <div ng-transclude></div></a>
    };
});

HTML

<sample>
    <div ng-include="some url"></div>
</sample>

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.