代码之家  ›  专栏  ›  技术社区  ›  Marvin

从表单中删除空字段和禁用字段的指令

  •  1
  • Marvin  · 技术社区  · 12 年前

    我试图从表单中隐藏所有输入被禁用且为空的“行”(即删除只读表单中未填充的字段)。

    从控制台使用jQuery很容易做到这一点:

    $('.input-group > input:disabled').each(function(){
        if($(this).val().length==0){
            $(this).parent('.input-group').remove();
        }
    });
    

    但是,当我想对它做出指示时,这就变得很棘手了(因为我的应用程序是AngularJs的,所以为了符合AngularJs)。

    基本上,每个字段都有这样的(引导)结构:

    <div class="input-group">
     <span class="input-group-addon">Field Label</spanS
     <input ng-disabled="someExpression" ng-model="someModel"/>
    </div>
    

    因此,我决定创建一个名为“inputGroup”的指令,该指令仅应用于匹配类('C'),如果其'input'被禁用且为空,则会删除该元素。。而且我无法让它工作,因为我从未能够在输入元素上找到一些工作的“禁用”属性。有一些“isContentEditable”和“disabled”属性,但无论输入状态如何,它们总是false。。。。

    因此,我仍在努力理解如何作为AngularJs指令来完成这个非常基本的(jQuery!)任务!欢迎任何提示!

    提前感谢。

    我的电流-不工作!-代码(混合了一些jQuery函数,因为我找不到任何其他角度兼容的方法):

    appDirectives.directive('inputGroup', function(){ 
        return { 
            restrict: 'C',
            link: function(element){            
                element.children('input:disabled').each(function(){
                        if($(this).val().length == 0){
                            $(this).parent('.input-group').remove();
                        }
                    });     
            } 
        } ;
    });
    

    编辑: 这里需要说明的是,模型是异步检索的(通过承诺),这一点很重要,我在评估指令时没有它的值。因此,我想手表必须在模型上。。。但不知道怎么做。

    1 回复  |  直到 12 年前
        1
  •  1
  •   Michael Bromley    12 年前

    首先,请注意,将传递给指令链接函数的第一个参数是 scope element 。更多信息: https://docs.angularjs.org/api/ng/service/$compile

    遵循为创建指令的方法 input-group ,这里是一个(粗略的)版本,它应该符合您的意图。

    app.directive('inputGroup', function() {
      return {
        restrict: 'C',
        link: function(scope, element, attrs) {
          var input = element.find('INPUT'); // get a reference to the input element so we can query its attributes. 
          var inputModel = input.attr('ng-model'); // get the expression in the input's ng-model attribute
          var disabledExpression = input.attr('ng-disabled'); // get the expression in the input's ng-disabled attribute
    
          scope.$watch(function() {
              return scope.$eval(disabledExpression);
            }, function(value) {
            if (!scope.$eval(inputModel) && scope.$eval(disabledExpression)) {
              element.addClass('hidden');
            } else {
              element.removeClass('hidden');
            }
          });
        }
      };
    });
    

    HTML将如下(与示例相同):

    <div class="input-group">
        <span class="input-group-addon">Field Label</span>
        <input ng-disabled="isDisabled" ng-model="someModel" />
    </div>
    

    演示: http://plnkr.co/edit/UArytXOLYyJhn70UodFe?p=preview

    删除输入

    在你的问题中,你谈到了如果输入组为空并且被禁用,那么实际上要删除它,而不是像我上面的代码那样隐藏它。要删除而不是隐藏,可以替换该行 element.addClass('hidden') 具有 element.remove() ,并删除else子句。