The directive template does not receive the values โ€‹โ€‹that are set by compilation

See this plunker

I have an html that uses a custom angular directive

<body ng-controller="myCtrl"> <h1>Hello Plunker!</h1> <div><sample attributeone="Sample Attribute"></sample></div> </body> 

and my directive is as follows:

 myApp.directive('sample', function() { var value = ""; return { replace: true, restrict: 'E', scope : false, template: '<div>This is a sample Paragraph '+ value + '</div>', compile: function ( tElement, tAttributes ) { return { pre: function preLink( scope, element, attributes ) { console.log( attributes.log + ' (pre-link)' ); value = tAttributes.attributeone; } }; } }; }); 

In my opinion, pre of compile must be executed before the template is returned, and value must be set to "Sample Attribute" . But this is not appreciated.

Expected Result

 This is a sample Paragraph Sample Attribute 

Actual output

 This is a sample Paragraph 

Is there any other way I set value in a template?

+7
javascript angularjs
source share
1 answer

If you just want to add value , then why not use your template as a function?

See this updated Plunker

 myApp.directive('sample', function() { var value = ""; return { replace: true, restrict: 'E', scope : false, template: function(ele, attr, ctrl) { value = attr.attributeone; return '<div>This is a sample Paragraph ' + value + '</div>'; } }; }); 
+2
source share

All Articles