Very new to AngularJS... I have an input field where I want the first letter to be capitalized. I added the below directive:
.directive('capitalizeFirst', function () {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, $modelCtrl) {
var capitalize = function (inputValue) {
var capitalized = angular.uppercase(inputValue.substring(0, 1)) + inputValue.substring(1);
if (capitalized !== inputValue) {
$modelCtrl.$setViewValue(capitalized);
$modelCtrl.$render();
}
return capitalized;
};
$modelCtrl.$parsers.push(capitalize);
capitalize($scope[$attrs.ngModel]); // capitalize initial value
}
};
})
It works! But it fires an error in my console:
TypeError: Cannot read property 'substring' of undefined
Can anybody let me know what is wrong? Thanks in advance!
Seems that you didn't check if inputValue is null.
.directive('capitalizeFirst', function () {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, $modelCtrl) {
var capitalize = function (inputValue) {
if (!! inputValue) {
var capitalized = angular.uppercase(inputValue.substring(0, 1)) + inputValue.substring(1);
if (capitalized !== inputValue) {
$modelCtrl.$setViewValue(capitalized);
$modelCtrl.$render();
}
return capitalized;
}
return inputValue;
};
$modelCtrl.$parsers.push(capitalize);
capitalize($scope[$attrs.ngModel]); // capitalize initial value
}
};})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With