Auto capitalize input char using attribute directive in AngularJs

Auto capitalize input char using attribute directive in AngularJs

Hello everyone, I am going to share the code sample for auto capitalize input char using attribute directive in AngularJs.

The live demo code link  http://embed.plnkr.co/2anvOl/

The code sample in detail as given below.

HTML code sample as given below

 <div ng-app="app">
    <div ng-controller="aapCtrl">
        Input TextBox:<input type="text" ng-model="name" capitalize-input-text>
    </div>
</div>

The example with attribute directive as given below

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.angularjs.org/1.4.9/angular.js"></script>
    <script>
        var app = angular.module("app", []);
        app.controller('aapCtrl', ["$scope", function ($scope) {
            $scope.name = 'Anil Singh';
        }]);

        app.directive('capitalizeInputText', function () {
            return {
                require: 'ngModel',
                link: function (scope, element, attrs, capitalizeModelCtrl) {

                    var capitalizeInputText = function (inputText) {
                        var capitalizedValue = inputText.toUpperCase();

                        if (inputText === undefined) {
                            inputText = "";
                        } else {
                            if (capitalizedValue !== inputText) {
                                capitalizeModelCtrl.$setViewValue(capitalizedValue);
                                capitalizeModelCtrl.$render();
                            }
                        }
                        return capitalizedValue;
                    }

                    capitalizeModelCtrl.$parsers.push(capitalizeInputText);
                    capitalizeInputText(scope[attrs.ngModel]); //This is used to capitalize the initial value.
                }
            };
        });
    </script>
</head>
<body ng-app="app">
    <div ng-controller="aapCtrl">
        Input TextBox:<input type="text" ng-model="name" capitalize-input-text>
    </div>
</body>

</html>



ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.