简单的自定义指令NG-属性添加到input元素 [英] Simple custom directive add ng-attribute to input element

查看:256
本文介绍了简单的自定义指令NG-属性添加到input元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图创建一个非常简单的指令来检查,如果属性我-MINLENGTH个是一个字符串(NOT NULL),如果是;属性 NG-MINLENGTH个添加到输入元素。我觉得这应该工作,但它仅仅是行不通的。

我的指令

  VAR应用= angular.module(fooApplication,[])app.directive('myMinlength',函数(){
    返回{
        链接:功能(范围,元素,ATTRS){
            如果(元素==){
                ATTRS $集('NG-MINLENGTH个',attrs.myMinlength)。
            }
        },
    }
});

我的HTML

 <输入类型=TEXTNAME =foo的我,MINLENGTH个=5要求/>

编辑建议从可能出现的错误完全剥离 - 仍然无法正常工作

  .directive('myMinlength',['$编译,函数($编译){
    返回{
        链接:功能(范围,元素,ATTRS){
           如果属实) {
                ATTRS $集('NG-MINLENGTH个,5)。
                $编译(元)(范围);
            }
        },
    }
}]);


解决方案

您可以用更简单的方法:

 <输入类型=TEXTNAME =foo的NG-= MINLENGTHMYVAR || 0要求/>

如果scope.myvar是不确定的,然后将MINLENGTH 0

I have been trying to create a very simple directive that checks if the attribute my-minlength is a string (not null) and if it is; add the attribute ng-minlength to the input element. I feel like this should work, but it is simply not working.

My Directive

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

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

My HTML

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

Edit the suggestion completely stripped from possible errors - still does not work.

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

解决方案

You can use simpler approach:

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

if scope.myvar is undefined then minlength will be 0

这篇关于简单的自定义指令NG-属性添加到input元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆