AngularJS Toggling Password Field
HTML
<div ng-app="app" ng-controller="ctrl">
<form name="pwForm">
<password-field toggle="hidePassword" ng-model="password" password-validator></password-field>
<div>Hide Password:
<input type="checkbox" name="togglePassword" ng-model="hidePassword"
/>
</div>
</form>
</div>
JavaScript
angular.module('app', [])
.controller('ctrl', function ($scope) {
$scope.hidePassword = false;
})
.directive('passwordField', function ($log, $browser, $sniffer) {
function isEmpty(value) {
return angular.isUndefined(value) || value === '' || value === null || value !== value;
}
return {
require: 'ngModel',
restrict: 'EA',
template: '<div><input type="text" /><input type="password" /></div>',
replace: true,
link: function (scope, el, attr, ctrl) {
var textInput = angular.element(el.children()[0]),
pwInput = angular.element(el.children()[1]);
var listener = function (e) {
var target = this,
value = angular.element(target).val();
if (ctrl.$viewValue !== value) {
scope.$apply(function () {
ctrl.$setViewValue(value);
ctrl.$render();
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
textInput.bind('input', listener);
pwInput.bind('input', listener);
} else {
var timeout;
var ev = function (event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
if (!timeout) {
timeout = $browser.defer(function () {
listener();
timeout = null;
});
}
};
textInput.bind('keydown', ev);
...