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?
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.
The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.
The ng-blur directive tells AngularJS what to do when an HTML element loses focus. The ng-blur directive from AngularJS will not override the element's original onblur event, both the ng-blur expression and the original onblur event will be executed.
<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">
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With