Created
October 15, 2016 15:09
-
-
Save matinfo/96747456aab36ea34c2681433a2f594c to your computer and use it in GitHub Desktop.
Handel max char left control for input and textarea with angularJS directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Handel max char left control for input and textarea | |
/* Set on your project this minumum css style (adapt for your need) | |
* mandatory for directive *maxlength-control* | |
*/ | |
/* | |
.maxlength-control ~ .maxlength-control-status { | |
color: #b5b5b5; | |
float: right; | |
} | |
.maxlength-control-input ~ .maxlength-control-status { | |
position: absolute; | |
top: 33px; | |
right: 30px; | |
color: #b5b5b5; | |
float: right; | |
} | |
.form-horizontal .maxlength-control-input ~ .maxlength-control-status { | |
top: 8px | |
} | |
.maxlength-control-status.maxlength-alert { | |
color: rgba(170, 30, 56, 0.6); // set your custom highlight color | |
} | |
// IE10+ | |
@media screen and (-ms-high-contrast: active), | |
(-ms-high-contrast: none) { | |
.form-horizontal .maxlength-control-input:focus~.maxlength-control-status { | |
right: 48px; | |
} | |
} | |
*/ | |
pmtApp.directive('maxlengthControl', ['$parse', '$compile', function($parse, $compile) { | |
return { | |
require: 'ngModel', | |
link: function(scope, element, attr, ngModel) { | |
var idP = Math.round(Math.random() * 1000000000), | |
alertAt = 0.1; | |
// add 'directive' class based of type of control | |
if (element.context.nodeName && element.context.nodeName === 'TEXTAREA') { | |
element.addClass('maxlength-control'); | |
alertAt = 0.03; // alert class less intrusif (UX opti) | |
} else { | |
element.addClass('maxlength-control-input'); | |
} | |
// inject initial status (set uniq ID) | |
element.after('<div class="maxlength-control-status" id="' + idP + '">0 / ' + attr.ngMaxlength + '</div>'); | |
// watch ngModel live change | |
scope.$watch(function() { | |
return ngModel.$viewValue; | |
}, | |
function(newValue) { | |
// change found | |
if (angular.isDefined(newValue)) { | |
// take calculation and set the status values | |
var remainingChar = attr.ngMaxlength - newValue.replace(/\r\n|\r|\n/g, "\r\n").length; | |
var remainText = remainingChar + " / " + attr.ngMaxlength; | |
// update status | |
angular.element('#' + idP).text(remainText); | |
// custom style if alert | |
if (remainingChar < (attr.ngMaxlength * alertAt)) { | |
angular.element('#' + idP).addClass('maxlength-alert'); | |
} else { | |
angular.element('#' + idP).removeClass('maxlength-alert'); | |
} | |
} | |
} | |
); | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment