【问题标题】:Easy way to transmit a custom directives' attributes to a child element?将自定义指令的属性传输到子元素的简单方法?
【发布时间】:2015-04-18 20:45:41
【问题描述】:

我正在创建一个指令,它基本上用作<input>,但具有一些特殊功能:

   app.directive('skInput', function(){
        return {
            restrict: 'A',
            replace:true,
            template: '<div style="display:inline-block">\
                        <span ng-show="disabled">{{model}}</span>\
                        <input ng-hide="disabled" placeholder="{{placeholder}}" type="text" class="sk-input" ng-model="model" stop-event ng-required="isRequired"/>\
                       </div>',
            require: ['ngModel'],
            scope:{
                'width':'@',
                disabled: '=ngDisabled',
                model: '=ngModel',
                placeholder: '@'
            },
            link: function(scope, elem, attrs){
                if(angular.isDefined(scope.width)){
                    elem.find('input').css('width', scope.width);
                }

                if(angular.isDefined(attrs.required)){
                    scope.isRequired = true;
                }else{
                    scope.isRequired = false;
                }
            }
        }
    });

问题是我想将此指令视为input,其中可能包含许多指令或HTML5 属性,如placeholder、ng-pattern、required 等。但是,我必须像您看到的那样手动将指令的属性连接到底层input。

有没有办法告诉 Angular 将指令上的属性放到 &lt;input&gt; 元素而不是 &lt;div&gt; 元素上?这样我就可以执行&lt;span sk-input ng-pattern="\regex\"&gt;&lt;/span&gt; 之类的操作,它会自动生成

<div>
    <span ng-show="disabled"></span>
    <input ng-pattern="\regex\" />
</div>

代替

<div ng-pattern="\regex\">
    <span ng-show="disabled"></span>
    <input />
</div>

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    我认为您只能手动操作,尽管可能有更简单的方法(您可能会考虑使用模板函数而不是字符串)。

    角度如何使用 replace: true 合并属性是内部的,实际上它们正在弃用。 Here is a related question。

    模板函数获取原始元素和属性。

    template: function(elem, attr) {
        var input = angular.element('<div><input></input></div>');
        for(var a in attr) {
            //optional if statement for whitelist/blacklist, etc.
            input.children().attr(a, attr[a]);
        }
        return '<div style="display:inline-block">\
                    <span ng-show="disabled">{{model}}</span>' +
                    input.innerHTML +
               '</div>'
        //build up your template here 
    }
    

    这样做甚至可以让您在不使用隔离作用域的情况下摆脱困境(这会使您的指令与其他 ng- 指令更加内联)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2017-02-24
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多