Skip to content

Instantly share code, notes, and snippets.

@evangalen
Last active December 23, 2015 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evangalen/6674352 to your computer and use it in GitHub Desktop.
Save evangalen/6674352 to your computer and use it in GitHub Desktop.
Plunk demonstrating a fix to render invalid values in a <input/> element; this effectively fixes AngularJS issue #1412 (= "input not showing invalid model values")
angular.module('plunker', ['jdFixInvalidValueFormatting']);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.1/angular.js" data-semver="1.2.1"></script>
<script src="jdFixInvalidValueFormatting.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker">
<div ng-init="letters='1'">
letters = {{'' + letters}}<br>
<input type="text" ng-model="letters" ng-pattern="/^[a-zA-Z]*$/" />
</div>
</body>
</html>
angular.module('jdFixInvalidValueFormatting', [])
.directive('input', function() {
return {
require: '?ngModel',
restrict: 'E',
link: function($scope, $element, $attrs, ngModelController) {
var inputType = angular.lowercase($attrs.type);
if (!ngModelController || inputType === 'radio' ||
inputType === 'checkbox') {
return;
}
ngModelController.$formatters.unshift(function(value) {
if (ngModelController.$invalid && angular.isUndefined(value)
&& typeof ngModelController.$modelValue === 'string') {
return ngModelController.$modelValue;
} else {
return value;
}
});
}
};
});
input.ng-invalid:focus {
border-color: #E9322D;
box-shadow: 0 0 6px #F8B9B7;
}
input.ng-invalid:not(:focus) {
background-color: #FA787E;
}
input.ng-pristine.ng-invalid-required {
background-color: white;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment