是否可以在angularjs中`directive`的`compile`中的`postLink`函数中为元素设置一些值?

时间:2013-01-28 15:22:07

标签: angularjs angularjs-directive

angularjs的文档:

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    priority: 0,
    template: '<div></div>',
    templateUrl: 'directive.html',
    replace: false,
    transclude: false,
    restrict: 'A',
    scope: false,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) {
                         // ????
                         // is it possible to set the content of iElement?
                    }
      }
    }
  };
  return directiveDefinitionObject;
});

postLink内的compile函数中,是否可以将一些文字设置为iElement

我试过了:

iElement.html("some");
iElement.textContent = "some";
jQuery(iElement).html("some");

但似乎没有一个有效。

1 个答案:

答案 0 :(得分:1)

iElement.html("some");应按预期工作:http://jsfiddle.net/bmleite/vjnN7/

app.directive('someDirective', function() {
  return {
    priority: 0,
    template: '<div>Test...</div>',    
    replace: false,
    transclude: false,
    restrict: 'A',
    scope: false,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {  },
        post: function postLink(scope, iElement, iAttrs, controller) {
                iElement.html('Some other test...');                         
             }
      }
    }
  };  
});