如何在使用模板时获取指令的原始内容?

时间:2014-10-08 23:22:26

标签: angularjs angularjs-directive

DEMO

根据模板的指令,我怎样才能获得原始内容?

例如:

HTML:

<div my-directive>
  <input type="text">
</div>

JS:

angular.module('App', []).directive('myDirective', function() {
  return {
    template: '<div>Template</div>',
    compile: function(element) {
      console.log(element.html()); // Outputs <div>Template</div>
      // How do I get <input type="text"> ?
    }
  };
});

PLAYGROUND HERE

3 个答案:

答案 0 :(得分:2)

因为你只是需要它用于显示目的而不是真正用它与绑定和其他东西,你需要它角度触摸它之前。您可以使用指令的template属性的函数表达式语法。

实施例: -

  var content;
  template: function(elm){
      content = elm.html(); //save the html
      return '<div>Template</div>';
   },

支持多个的扩展示例: -

.directive('myDirective', function($timeout) {
  var content={};
  var loadedDirs;
  return {
    scope:true,
    template: function(elm){
      loadedDirs = loadedDirs || 
                   angular.element(document.querySelectorAll('[my-directive]'));
       //Save the element in its respective index    
      content[loadedDirs.index(elm)] = elm.html();

      return '<div>Template<div><pre>{{orig}}</pre></div></div>'
    },
    link: function(scope, element) {
      var idx = loadedDirs.index(element);
       scope.orig = content[idx];

       //Remove key
       delete content[idx];
       //Remove reference to loadedDirs
       if(!Object.keys(content)){ 
         loadedDirs = null;
        }  
      }
  };
});

<强> Demo

没有Jquery解决方案(适用于index

.directive('myDirective', function($timeout) {
  var content={},
      idx = 0;

  return {
    scope:true,
    template: function(elm){
      elm.idx = idx; //set an iterative index
       //Save the element in its respective index    
      content[idx++] = elm.html(); //save element html in a map

      return '<div>Template<div><pre>{{orig}}</pre></div></div>'
    },
    link: function(scope, element) {
      var idx = element.idx; //Get idx property value from the element
       scope.orig = content[idx]; //get the content
      delete content[idx]; //remove the key
      if(!Object.keys(content)){ idx = 0; } //reset idx once all are loaded
     }
  };
});

<强> Demo

答案 1 :(得分:0)

您可以使用ng-transclude,docs here。您将获得附加到指令模板内容的原始内容。

答案 2 :(得分:0)

检查一下(你必须将transclude设置为true)

angular.module('App', []).directive('myDirective', function() {
  return {
    template: '<div>template</div>',
    transclude: true,
    link: function(scope, element, attr, ctrl, transclude) {
      transclude(scope, function(clone){
       var html = '';
        for(var i = 0; i<clone.length;i++){
          html +=  clone[i].outerHTML || '';
        }
        console.log(html);
      })

    }
  };
});