javascript – Directive的模板没有获得由compile设置的值

前端之家收集整理的这篇文章主要介绍了javascript – Directive的模板没有获得由compile设置的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请看这 Plunker

我有一个使用自定义角度指令的HTML

  1. <body ng-controller="myCtrl">
  2. <h1>Hello Plunker!</h1>
  3. <div><sample attributeone="Sample Attribute"></sample></div>
  4. </body>

我的指令看起来像这样:

  1. myApp.directive('sample',function() {
  2. var value = "";
  3. return {
  4. replace: true,restrict: 'E',scope : false,template: '<div>This is a sample Paragraph '+ value + '</div>',compile: function ( tElement,tAttributes ) {
  5. return {
  6. pre: function preLink( scope,element,attributes ) {
  7. console.log( attributes.log + ' (pre-link)' );
  8. value = tAttributes.attributeone;
  9. }
  10. };
  11. }
  12. };
  13. });

在我看来,编译前应该执行bofore返回模板,值应该设置为“Sample Attribute”.但它没有得到评估.

预期产出

  1. This is a sample Paragraph Sample Attribute

实际产出

  1. This is a sample Paragraph

有没有其他方法可以在模板中设置值?

解决方法

如果您只想附加值,那么为什么不将您的模板用作函数

请参阅此更新的Plunker

  1. myApp.directive('sample',template: function(ele,attr,ctrl) {
  2. value = attr.attributeone;
  3. return '<div>This is a sample Paragraph ' + value + '</div>';
  4. }
  5. };
  6. });

猜你在找的JavaScript相关文章