javascript - 如何将指令模板的属性附加到 AngularJS 中父元素以外的其他元素?

标签 javascript jquery html angularjs

我想实现一个转换指令 <specialInput></specialInput>变成类似

<div id="myDiv">
    <label></label>
    <input></input>
</div>

但是,用户通过将其放入 specialInput 来提供的所有属性- 标签如 <specialInput id="test" class="test2" ... required></specialInput>当前附加到 div 元素 myDiv。 相反,我想将所有属性附加到 input -标签。

注意:一种解决方案是通过将变量(例如 type="' + atts.type + '" )添加到模板来手动将每个可能的属性附加到标签标记,然后使用 linkfunction 从父级中删除这些属性。但这不是我想要实现的目标。有太多可能的属性需要考虑此解决方案。

// special-input Angular


(function () {
  'use strict';

  function specialInputDirective($compile) {

    function templateFunction(element, attrs) {
      var template = [
       '<div class="control-group">'+
       '<label for="' + attrs.name + '" class="control-label">' + attrs.label + '</label>' +
       ' <div class="controls">' +
       '  <input id="' + attrs.id + '" type="' + attrs.type + '" ' +                                            
       '       ng-model="' + attrs.name + '" ' +
       (attrs.ngTrueValue ? 'ng-true-value="' + attrs.ngTrueValue + '" ' : '') +
       (attrs.ngFalseValue ? 'ng-false-value="' + attrs.ngFalseValue + '"' : '') +
       ' " placeholder="' + attrs.placeholder + '"' + ' ' +
       attrs.required + ' ' + attrs.disabled + ' ' + attrs.readonly  +
       ' name="' + attrs.name + '"' +
       ' required>' +
       ' </div>' +
       '</div>'
      ].join('');
      return template;
    }

    return {
      link: linkFunction,
      restrict: 'E',
      replace: true,
      transclude: true,
      template: templateFunction
    };

    //////////

    function linkFunction(scope, inputElement, attrs, ctrl, transcludeFn) {
      // Removes user defined attributes from 'control-group'.
      // These are added to the <input> element instead (Defined in: Template)
      // BUT: there are many, many more attributes than this! So this is not the solution I'm aiming for.
      inputElement.removeAttr('id');
      inputElement.removeAttr('type');
      inputElement.removeAttr('label');
      inputElement.removeAttr('placeholder');
      inputElement.removeAttr('required');
      inputElement.removeAttr('disabled');
      inputElement.removeAttr('readonly');
      inputElement.removeAttr('name');
    }
  }


  //////////

  function initModule(angular) {
    ...
  }

}());
<form name="myForm" class="form-horizontal" style="max-width: 700px;">
    <h4>Horizontal Label</h4>
    <special-input name="myName" type="email" label="Email" placeholder="Email"></special-input>
    <special-validation for="myForm.myName" message="required" type="error">This message box represents an error</special-validation>
    <special-validation for="myForm.myName" message="minlength" type="warning">This message box represents a warning</special-validation>
    <special-validation for="myForm.myName" message="maxlength">This message box represents an error</special-validation>
    <special-validation for="myForm.myName" message="email">Invalid email address</special-validation>

    <special-input type="text" label="Text" placeholder="Required input" name="myName2" ng-minlength="5" ng-maxlength="20" required></special-input>

    <special-input type="password" label="Password" placeholder="Password"></special-input>
</form>

最佳答案

您绝对不想在范围中为每个属性创建绑定(bind)。相反,最简单也可能是最有效的解决方法是找到一个输入元素,然后在编译函数中将所有属性复制到它。

这是您的指令的简化版本:

.directive('specialInput', function() {

    function linkFunction(scope, element, attrs) {
        // Do something else, bind events, etc ...
    }

    return {
        transclude: true,
        template: function(element, attrs) {
            return '' +
            '<div class="control-group">' +
            '    <label for="' + attrs.name + '">' + attrs.label + '</label>' +
            '    <input>' +
            '</div>';
        },
        compile: function(element, attrs) {

            var input = element.find('input');

            // Copy attrbutes
            angular.forEach(attrs.$attr, function(val, key) {
                input.attr(val, attrs[key]);
            });

            element.replaceWith(element.children()[0]);

            return linkFunction;
        }
    };
});

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

关于javascript - 如何将指令模板的属性附加到 AngularJS 中父元素以外的其他元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34083889/

相关文章:

javascript - 使用 <p> 标签包装 JQuery 函数结果

php - html post form action 没有专门拼出来的php文件?

javascript - 文件名中 $Revision$ 的 IE6 Javascript 问题

javascript - 如果数字为 0,则针对空的测试失败

javascript - 使用事件委托(delegate)处理不规则形状对象上的鼠标事件

javascript - 我进行了 AJAX 调用,并且 jQuery 在调用后不再添加类

javascript - jQuery 选择器规则是否会针对较新的浏览器发生变化?

javascript - 希望在单击幻灯片上的下一个/上一个按钮后立即在图像上显示文本

javascript - 多次 AJAX 调用后执行代码

javascript - 为什么单击按钮时会运行两个函数而不是一个?