Skip to content

Instantly share code, notes, and snippets.

@evangalen
Last active December 23, 2015 18:19
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/6674554 to your computer and use it in GitHub Desktop.
Save evangalen/6674554 to your computer and use it in GitHub Desktop.
Plunk demonstrating a fix for AngularJS issue #1412 (= "input not showing invalid model values") as well a fix 2 inconsistencies in the parsing of data entry.
angular.module('plunker', ['jdFixInvalidValueFormatting', 'jdFixParsingInconsistencies']);
<!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="jdFixParsingInconsistencies.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;
}
});
}
};
});
angular.module('jdFixParsingInconsistencies', [])
.directive('input', function() {
return {
priority: (angular.version.full.indexOf('1.2.') === 0 && angular.version.full !== '1.2.0rc1' && angular.version.full !== '1.2.0-rc.2') ? 1 : 0,
require: '?ngModel',
restrict: 'E',
link: function($scope, $element, $attrs, ngModelController) {
var inputType = angular.lowercase($attrs.type);
if (!ngModelController || inputType === 'radio' ||
inputType === 'checkbox') {
return;
}
ngModelController.$parsers.push(function(value) {
if ((ngModelController.$invalid && angular.isUndefined(value)) || value === '') {
return null;
} 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