Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive's template doesn't get value that's set by compile

Please see this Plunker

I have an html that uses custom angular directive

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

and my directive looks like this:

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, the pre of compile should execute bofore the template is returned and value should be set to "Sample Attribute". But it's not getting evaluated.

Expected Output

This is a sample Paragraph Sample Attribute

Actual Output

This is a sample Paragraph

Is there any other way through which I set the value in template?

like image 284
Tom Hulme Avatar asked Jul 21 '16 08:07

Tom Hulme


1 Answers

If you just want to append 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>';
            }
        };
});
like image 92
Raman Sahasi Avatar answered Oct 30 '22 13:10

Raman Sahasi