AngularJS中的< input>元素上的ng-type/show-password指令 [英] ng-type / show-password directive on `<input>` element in angularjs

查看:96
本文介绍了AngularJS中的< input>元素上的ng-type/show-password指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在输入元素上使用数据绑定,如下所示:

We can use data-binding on input elements like this:

<input type="{{ showPassword ? 'text' : 'password' }}" name="password">

但这与在href属性上使用数据绑定有类似的问题(请参阅ngHref ).这样,在dom中会有一个类型为{{ showPassword ? 'text' : 'password' }}的输入元素,直到出现角负载为止.像ngHref这样具有ngType指令看起来很方便,可以这样使用:

But this has similar problems as using data-binding on a href attribute (see ngHref). This way there is an input element in the dom with the type {{ showPassword ? 'text' : 'password' }} until angular loads. It looks convenient to have an ngType directive much like ngHref, what could be used this way:

<input type="password" ng-type="{{ showPassword ? 'text' : 'password' }}" name="password">

还有其他方法可以做到吗?我必须实现这个ngType事情吗?

Is there any other way to do it? Do I have to implement this ngType thing?

推荐答案

更改<input>类型的自定义指令:

要显示或隐藏密码,请使用自定义指令:

Custom directive that changes the <input> type:

To show or hide the password use a custom directive:

app.directive("showPassword", function() { 
    return function linkFn(scope, elem, attrs) {
        scope.$watch(attrs.showPassword, function(newValue) {
            if (newValue) {
                elem.attr("type", "text");
            } else {
                elem.attr("type", "password");
            };
        });
    };
});

用法

 <input type=password show-password="showPassword" 
        ng-model="thePassword">

show-password指令监视已定义的作用域变量,并在为true时将输入更改为type=text,在为false时将输入更改为type=password.

The show-password directive watches the defined scope variable and changes the input to type=text when truthy and back to type=password when falsey.

angular.module("myApp",[])
.directive("showPassword", function() { 
    return function linkFn(scope, elem, attrs) {
        scope.$watch(attrs.showPassword, function(newValue) {
            if (newValue) {
                elem.attr("type", "text");
            } else {
                elem.attr("type", "password");
            };
        });
    };
})

<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app='myApp'>

    <button ng-click="showPassword = true">Show Password</button><br>
    <button ng-click="showPassword = false">Hide Password</button><br>
    
    <input type=password show-password="showPassword" 
           ng-model="thePassword">
    <hr>
    PASSWORD == {{thePassword}}
</div>

这篇关于AngularJS中的&lt; input&gt;元素上的ng-type/show-password指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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