angularjs ng-form inside指令

时间:2014-08-03 07:07:53

标签: angularjs angularjs-directive

我有一个自定义表单指令,在其中创建一个ng-form。我想在转换元素中使用此表单,禁用按钮等,但它不起作用.. PLUNKER LINK

app.directive("myform", function(){

  var templateFn = function(tElement, tAttrs){
    var html = '<div ng-form="' + tAttrs.name + '">' 
    html += '<div ng-transclude=""></div>'
    html += '</div>'
    return html;
  };

  return {
    restrict: 'E',
    template: templateFn,
    scope: {list: '='},
    transclude: true
  }

});

这就是我使用它的方式

<myform name="example">
   <input type="text" required ng-model="name2"/>
   <button ng-disabled="example.$invalid"> button </button>        
</myform> 

我需要在链接期间编译模板吗?我认为当使用模板并且后面发生链接时,$ compile会处理这个......

生成的html与预期一致,但该按钮未被禁用

     <myform name="example" class="ng-isolate-scope">
     <div ng-form="example" class="ng-pristine ng-invalid ng-invalid-required">
       <div ng-transclude="">
             <input type="text" required="" ng-model="name2" class="ng-scope ng-pristine ng-invalid ng-invalid-required">
             <button ng-disabled="example.$invalid" class="ng-scope"> button </button>
       </div>
       </div>
     </myform>

1 个答案:

答案 0 :(得分:1)

当你转换内容时,让它链接到与ng-form相同的隔离范围(而不是默认的父范围):

app.directive("myform", function(){

  var templateFn = function(tElement, tAttrs){
    var html = '<div ng-form="' + tAttrs.name + '">' 
    html += '<div></div>'
    html += '</div>'
    return html;
  };

  return {
    restrict: 'E',
    template: templateFn,
    scope: {list: '='},
    transclude: true, 
    link:function(scope, element, attr, ctrl, transcludeFn) {
      var e = element.find('div');

      transcludeFn(scope, function(clone) {
        angular.element(e[1]).append(clone);
      });
    }
  }

});

Demo Plunker