Search code examples
htmlcssangularjscapitalize

How to capitalize and uppercase in AngularJS?


I want to capitalize/uppercase some fields in a HTML form.

HTML

<form role="form" ng-submit="submit()">
    <input type="text" class="capitalize" ng-model="first"/>
    <input type="text" class="uppercase" ng-model="last"/>
    <button type="submit"></button>
</form>

CSS

.uppercase {
    text-transform: uppercase;
}

.capitalize {
    text-transform: capitalize;
}

When I enter data on the fields it works well, but when form is submitted, capitalization is not preserved.

I use an Angular controller/service to send data to my server. Should I edit data on my controller, or could I keep the CSS capitalization ?

Thanks! :)


Solution

  • Here is a solution. Add to your controller those 2 new functions:

    function upperCase(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
    
    function capitalize(str) {
        return str.toUpperCase();    
    }
    

    In $scope.submit(), You can transform the firstname/lastname as following:

    $scope.submit = function() {
        ...
        $scope.firstname = upperCase($scope.firstname);    
        $scope.lastname = capitalize($scope.lastname);
    }