angularjs - Provide template with expressions as attribute on directive -
i'm wanting pass "template" directive, means of attribute. here's trite example of i'm trying accomplish:
this html:
<greeter person-name="jim" greeting-template="hello {{name}}"></greeter> would produce output: hello jim.
i've tried directive this:
function greeter($interpolate) { var directive = { link: link, restrict: 'ea', template: '<div>{{evaluatedtemplate}}</div>' }; return directive; function link(scope, element, attrs) { scope.name = attrs.personname; scope.evaluatedtemplate = $interpolate(attrs.greetingtemplate)(scope); } } but doesn't work, because {{name}} in greeting-template attribute gets evaluated in parent scope before gets far directive link function.
ultimately, need value of attrs.greetingtemplate literally string of: 'hello {{name}}'. figure alternative syntax, having greeting-template attribute value as: "hello [name]" , convert "[" "{{" before interpolation. feels messy. looked @ transclusion too, way evaluates directive against parent scope looks cause issues when have multiple greeter's.
instead of using link function, use compile function, runs before linking scope occurs, , gets passed template element (the original dom element) uninterpolated attributes arguments. think that's you're looking here.
in compile function, store uninterpolated template string in variable later use in post-link function (which same link function if use link rather compile), can bind scope.
so directive this, compile property rather link property:
function greeter($interpolate) { var directive = { compile: compile, restrict: 'ea', scope: true, template: '<div>{{evaluatedtemplate}}</div>' }; return directive; function compile(telement, tattrs) { // save uninterpolated template use in our post-link function var greetingtemplateuninterpolated = tattrs.greetingtemplate; return { pre: function (scope, element, attrs) {}, post: function (scope, element, attrs) { scope.name = attrs.personname; scope.evaluatedtemplate = $interpolate(greetingtemplateuninterpolated)(scope); } }; } } here's fiddle showing working.
and here's article explaining how compile , link work.