【问题标题】:Simple custom directive add ng-attribute to input element简单的自定义指令将 ng-attribute 添加到输入元素
【发布时间】:2014-07-07 12:25:32
【问题描述】:

我一直在尝试创建一个非常简单的指令来检查属性my-minlength 是否为字符串(非空)以及是否为;将属性ng-minlength 添加到输入元素。我觉得这应该可行,但它根本行不通。

我的指令

var app = angular.module("fooApplication", [])

app.directive('myMinlength', function() {
    return {
        link: function(scope, element, attrs) {
            if(element == "") {
                attrs.$set('ng-minlength', attrs.myMinlength);
            }
        },
    }
});

我的 HTML

<input type="text" name="foo" my-minlength="5" required/>

编辑建议完全消除可能的错误 - 仍然不起作用。

.directive('myMinlength', ['$compile', function($compile) {
    return {
        link: function(scope, element, attrs) {
           if(true) {
                attrs.$set('ng-minlength', "5");
                $compile(element)(scope);
            }
        },
    }
}]);

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    您可以使用更简单的方法:

    <input type="text" name="foo" ng-minlength="myvar || 0" required/>
    

    如果 scope.myvar 未定义,则 minlength 将为 0

    【讨论】:

    • 你不知道你刚刚为我节省了多少时间——如果能找出其他方法不起作用的原因就好了!
    • 这将无济于事,例如,如果您打算将 'checked' 属性添加到单选按钮(因为即使 checked="false" 也会检查它)。在这种情况下,检查一个专用的角度指令(在这种情况下是 ng-checked)。
    【解决方案2】:

    您需要重新编译指令才能将 ng-minlength 属性添加到指令中。试试这个:

    .directive('myMinlength', ['$compile', function($compile) {
                    return {
                        link: function(scope, element, attrs) {
                           if(element == "") {
                                attrs.$set('ng-minlength', attrs.myMinlength);
                                $compile(element)(scope);
                            }
                        },
                    }
                }]);
    

    【讨论】:

    • 我在表单输入指令中使用它。当使用 $compile(element)(scope);它有效,但我得到未定义的
    【解决方案3】:

    你应该使用编译

     .directive('myMinlength', function() {
        var directive = {};
    
        directive.restrict = 'A'; /* restrict this directive to attributess */
    
        directive.compile = function(element, attributes) {
    
    
            var linkFunction = function($scope, element, attributes) {
               attributes.$set('ng-minlength', attrs.myMinlength);
            }
    
            return linkFunction;
        }
    
        return directive;
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2018-07-03
      相关资源
      最近更新 更多