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

时间:2015-12-04 08:29:36

标签: 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 + '")添加到模板,然后通过使用从父项中删除这些属性,将每个可能的属性手动附加到label标签链接功能。这不是我想要达到的目标。考虑这个解决方案有太多可能的属性。

&#13;
&#13;
// 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) {
    ...
  }

}());
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

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

以下是您的指令的简化版本:

.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

答案 1 :(得分:1)

您必须使用指令的编译功能来实现您想要的功能。

只要您只想将PLAIN ATTRIBUTES从父元素移动到内部,您基本上就可以了。如果要将DIRECTIVES属性从父级移动到子级,则会更复杂。

第一个选项的例子(只有plain / html属性,不需要在子元素上编译/链接的东西):

/**
 * Input wrapper directive, used to copy all attributes to the underneath input element.
 *
 * To keep a property on the wrapper, prefix it with "wrapper-*"
 * In example, "wrapper-class" will create the "class" property on the wrapper, where "class" will be copied to the input.
 */
module.directive("tlInputWrapper", function($compile) {
    // TODO : keep ngShow, ngIf... and other logic directive on the wrapper.
    return {
        restrict : "A",
        compile  : function($el, $attrs) {

            var input = $el.find("input"); // here, you find the child element you wanna move attributes to

            $attrs.$set("tlInputWrapper", null);
            var attributesToKeep = {};

            _.each($attrs.$attr, function(domAttributeName, normalizedAttributeName) {
                if(domAttributeName.indexOf("wrapper-") === 0) { // I allow keeping attributes on the wrapper. Ex : 'wrapper-class' will stay on the wrapper and be renamed 'class'
                    attributesToKeep[domAttributeName.substring(8)] = $attrs[normalizedAttributeName];
                    $attrs.$set(normalizedAttributeName, null);
                } else {
                    input.attr(domAttributeName, $attrs[normalizedAttributeName]);
                    $attrs.$set(normalizedAttributeName, null);
                }
            });

            _.each(attributesToKeep, function(attrValue, attrName) {
                $attrs.$set(attrName, attrValue);
            });

            return angular.noop;
        }
    };
});