angularjs 中`<input>` 元素上的ng-type/show-password 指令 [英] ng-type / show-password directive on `<input>` element in angularjs
问题描述
我们可以像这样在输入元素上使用数据绑定:
但这与在 href
属性(参见 ngHref).这样,dom 中有一个输入元素,其类型为 {{ showPassword ?'text' : 'password' }}
直到角度加载.ngType
指令看起来很方便,很像 ngHref
,可以这样使用:
还有其他方法吗?我必须实现这个 ngType
的东西吗?
改变
类型的自定义指令:
要显示或隐藏密码,请使用自定义指令:
app.directive(showPassword", function() {返回函数linkFn(范围,元素,属性){scope.$watch(attrs.showPassword, function(newValue) {如果(新值){elem.attr(类型",文本");} 别的 {elem.attr(类型",密码");};});};});
用法
show-password
指令监视定义的范围变量,并在 true 时将输入更改为 type=text
并返回到 type=password
假的时候.
演示
angular.module("myApp",[]).directive("showPassword", function() {返回函数linkFn(范围,元素,属性){scope.$watch(attrs.showPassword, function(newValue) {如果(新值){elem.attr("类型", "文本");} 别的 {elem.attr("类型", "密码");};});};})
<script src="//unpkg.com/angular/angular.js"></script><div ng-app='myApp'><button ng-click="showPassword = true">显示密码</button><br><button ng-click="showPassword = false">隐藏密码</button><br><input type=password show-password="showPassword"ng-model="密码"><小时>密码 == {{thePassword}}
We can use data-binding on input elements like this:
<input type="{{ showPassword ? 'text' : 'password' }}" name="password">
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">
Is there any other way to do it? Do I have to implement this ngType
thing?
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");
};
});
};
});
Usage
<input type=password show-password="showPassword"
ng-model="thePassword">
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.
The 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");
};
});
};
})
<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 中`<input>` 元素上的ng-type/show-password 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!