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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book