Using angular js here:
I have a HTML table and using contenteditable for each row data, eg as below:
<td contenteditable="true"
ng-repeat="column in targetTable.columns"
ng-model="r[column.id]"
ng-blur="!r.id? addNewRow(r[column.id], r): undefined">
</td>
I also have my directive as:
directive('contenteditable', ['$sce', function($sce) {
return {
link: function(scope, element, attrs, ngModel) {
var regex = /^[\w/\s_~`!@#$%^&*()_+-={}[\]|\:;/>\\\'\"]$/;
element.on('keypress', (e) => {
char = String.fromCharCode(event.which);
if (!regexpInt.test(char)) {
event.preventDefault();
};
});
ngModel.$parsers.push(function (value) {
if (value.length > 5) {
value = value.substr(0, 5);
ngModel.$setViewValue(value);
ngModel.$render();
}
return value;
});
}
}
});
I am just posting relevant code from the directive. The entire working code can be seen in the code pen below.
In the above directive I am using regex to allow user to type anything from the character set defined along with spl chars and space which works fine.
I am also using ngModel.$parsers trying to restrict the user entry to certain character limit (5 in this case), so if the user types more than 5, I want to the input to stop accepting more chars. The reason to apply limit here is this I would be creating dynamic columns and based on the column name I would be applying the maxlength of each so I cannot apply the limit on the in the html.
Now the issue comes with the maxlength code, it works not exactly as expected.
If you see the demo and start typing more than 5 characters, as soon as you type the 6th character the cursor comes to 1st character and keeps overwriting the existing if you type more chars.
Since I want to allow space in the input, if you type some char and add space it tries to add & n b s p; to the input.
What I want from the maxlength code is, it should accept spaces and as soon as you try to type more than 5th char it would prevent the user to typing and stop there itself. Similar to regex code.
Here is my below codepen demo: https://codepen.io/anon/pen/WKZJWw
Any inputs for fixing this issue?