angularjs中`<input>`元素的ng-type/show-password指令

Tam*_*dus 6 angularjs angularjs-directive

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

<input type="{{ showPassword ? 'text' : 'password' }}" name="password">
Run Code Online (Sandbox Code Playgroud)

但是这与在href属性上使用数据绑定有类似的问题(参见ngHref).这样,dom中的输入元素具有{{ showPassword ? 'text' : 'password' }}直到角度载荷的类型.有一个ngType指令很方便ngHref,可以这样使用:

<input type="password" ng-type="{{ showPassword ? 'text' : 'password' }}" name="password">
Run Code Online (Sandbox Code Playgroud)

还有其他办法吗?我必须实现这个ngType东西吗?

geo*_*awg 7

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

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

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");
            };
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

用法

 <input type=password show-password="showPassword" 
        ng-model="thePassword">
Run Code Online (Sandbox Code Playgroud)

show-password指令type=text监视已定义的范围变量,并将输入更改为truthy,并type=password在falsey时更改为.

DEMO

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");
            };
        });
    };
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)