Ng-type / show-password directive on the `<input>` element in angularjs

We can use data binding to input elements as follows:

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

But this has similar problems, like using data binding to the href attribute ( see ngHref ). So dom uses an input element of type {{ showPassword ? 'text' : 'password' }} {{ showPassword ? 'text' : 'password' }} until angular is loaded. It is convenient to have the ngType directive very similar to ngHref , which can be used as follows:

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

Is there any other way to do this? Should I implement this ngType thing?

+5
source share
1 answer

A custom directive that changes the type of <input> :

To show or hide the password, use the 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"); }; }); }; }); 

Using

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

The show-password directive monitors the specified scope variable and changes the input to type=text when editing and back to type=password when false.

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> 
+3
source

All Articles