Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : Cannot read property 'substring' of undefined

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!

like image 206
MrUpsidown Avatar asked Mar 19 '26 06:03

MrUpsidown


1 Answers

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
    }
};})
like image 106
tousvena Avatar answered Mar 21 '26 20:03

tousvena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!