Automatic capitalization feature for input fields implemented with AngularJS

I have integrated a directive into my input field to validate a license key against a server-side API. While this functionality works well, I also want the license key to automatically add hyphens and appear in capital letters.

For example, when a user inputs abcd1234qwer5678, it should display as ABCD-1234-QWER-5678. (I am focusing on achieving auto-capitalization first, then I will work on adding hyphens).

I have attempted a few approaches. Initially, I tried using a $watch function within the controller:

$scope.$watch('licenceKey', function (newValue, oldValue) {
    $scope.$apply(function () {
        $scope.licenceKey = newValue.toUpperCase();
    })
});

Additionally, I explored using a second directive applied to the input:

myApp.directive('capitalize', function() {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
           if(inputValue == undefined) inputValue = '';
           var capitalized = inputValue.toUpperCase();
           if(capitalized !== inputValue) {
              modelCtrl.$setViewValue(capitalized);
              modelCtrl.$render();
            }         
            return capitalized;
         }
         modelCtrl.$parsers.push(capitalize);
         capitalize(scope[attrs.ngModel]);  // capitalize initial value
     }
   };
});

The first approach doesn't seem to have any effect, while the second one replaces the existing text after a brief delay. The HTML for my input field is as follows:

<input type="text" name="licenceKey" ng-model="licenceKey" 
    ng-model-options="{ debounce : { 'default' : 150 } }" licence-key-validator />

What is the most effective way to achieve the desired outcome, and what could be causing these challenges?

I have noticed that when using Batarang to inspect the scope, the licenceKey remains null until I submit the form. Why isn't it being populated as I type into the input field?

angular.module('licenceApp.controllers', [])
    .controller('licenceController', ['$scope', 'licenceAPIservice', '$filter', function ($scope, licenceAPIservice, $filter) {
        $scope.licenceKey = "";

        $scope.$watch('licenceKey', function (newValue, oldValue) {
            $scope.$apply(function () {
                $scope.licenceKey = newValue.toUpperCase();
            })
        });
        ...

Update

I just realized that when using the watch method, the text doesn't get capitalized until a valid license key (validated by the licenceAPIservice) is entered. However, it does capitalize correctly when entering a lowercase valid key. See the code snippet below:

angular.module('licenceApp.directives', [])
    .directive('licenceKeyValidator', function ($http, $q, licenceAPIservice) {
        return {
            require: 'ngModel',
            link: function ($scope, element, attrs, ngModel) {
                ngModel.$asyncValidators.licenceKeyValidator = function (licenceKey) {
                    var deferred = $q.defer();

                    licenceAPIservice.validateKey(licenceKey).then(function (data) {
                        if (data.data) {
                            deferred.resolve();
                        }
                        else {
                            deferred.reject();
                        }
                    }, function () {
                        deferred.reject();
                    });

                    return deferred.promise;
                };
            }
        }
    });

Answer №1

I have successfully developed a compact function by utilizing a custom filter that both capitalizes and hyphenates. Feel free to review the code below and let me know if it aligns with your requirements.

http://plnkr.co/edit/u6NTYRakWbojg3pQxzkH?p=preview

Code:

var app = angular.module("myApp", []);

app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter){

  $scope.myText = "";

  $scope.update = function(){ 
    $scope.myText = $filter('myFilter')($scope.myText); 
  };

}]); 

app.filter('myFilter', function(){
  return function(text){
    if(!text)
      return text;
    else{
      var processedText = text;
       processedText = processedText.toUpperCase().replace('', '');
      if(processedText.length > 4 && processedText[4] !== "-") 
        processedText = processedText.substring(0, 4) + "-" + processedText.substring(4);
      if(processedText.length > 9 && processedText[9] !== "-") 
        processedText = processedText.substring(0, 9) + "-" + processedText.substring(9);
      if(processedText.length > 14 && processedText[14] !== "-") 
        processedText = processedText.substring(0, 14) + "-" + processedText.substring(14); 
      return processedText; 
    }
  }; 
});

HTML:

<input ng-model="myText" ng-change="update()"/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

set available date with angular bootstrap datetimepicker

Currently, I am utilizing an angular bootstrap datetimepicker plugin that can be found at https://github.com/dalelotts/angular-bootstrap-datetimepicker. My goal is to configure the calendar so that only dates within the range of today and seven days in t ...

Identify and track colored dots within an image using tracking.js

I'm working on creating a program that can tally the number of dots on dominoes in an image, such as the one shown here: My goal is to develop this functionality using JavaScript. I've attempted to learn how to utilize tracking js through variou ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code ...

Conceal a specific class from being seen by another class of the same name upon clicking

I have a webpage with multiple images all sharing the same class name. When I try to hide a specific image by clicking on it, all images with that class are affected. Even though I used PHP to display the images on the webpage, I haven't been able to ...

Tips for sending an object in AngularJS to the HTTPOST method

I am facing an issue where I am trying to pass an object to my controller using the $http method, but even though the object has a value, the data being passed is showing as NULL. Below is the code snippet that demonstrates this problem. Within my JavaScr ...

Transform ng-switch with the power of links

Is there a way to activate an ng-switch using hyperlinks? This is my current HTML setup: <ul class="nav nav-list bs-docs-sidenav affix sidenav"> <li><a href="#" ng-click="page='resources'">Resources</a></li> ...

Issue: Route.get() is expecting a callback function, but instead received an undefined object in app.js

It's puzzling why this error is occurring. I have another model with a similar route and controllers, but it's not working as expected. The error message reads: Error: Route.get() requires a callback function but got a [object Undefined] at Route ...

Angular ERROR: Trying to access rating property of an undefined value

I'm encountering an issue on a website where users can vote for their favorite animal. Whenever I try to select an animal to vote for, I receive an unclear error message that has been difficult to resolve even after searching online for a solution. A ...

The Challenge with jQuery Radio Buttons

I am currently using jQuery to toggle the visibility of a div element. However, I am facing an issue where the else condition is being executed even when it should not be. I am unsure of what mistake I may have made in my code. Any help would be greatly ap ...

Unable to locate phonepe.intentsdk.android.release:IntentSDK:2.4.1 while integrating React Native

android build gradle : // Configuration options for all sub-projects/modules are defined in the top-level build file. buildscript { ext { buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = ...

Updates made in the angular controller are not reflecting on the HTML page

I am facing an issue with displaying a "no internet access" button in my app when the user is offline and the required object is not available in the cache. Here is the HTML code: <div class="VideoPlayerController video-player-controller"> <span ...

Top strategies for efficiently managing the loading of extensive PHP pages using Jquery, Ajax, HTML, and other tools

Hey there, I hope you're doing well in this new year. I've been working on a project that creates a "league table" using a large amount of data, similar to those seen in sports like football. The backend is built in PHP to process the data and d ...

Utilizing AJAX for fetching a partial view

My Web Forms legacy project had a feature where a panel would be displayed when the user clicked on a button. Now, I am working on rebuilding this functionality in C# MVC. The new view will utilize Javascript and AJAX to display a partial view as needed. ...

Which JQuery plugins can transform regular <select> dropdowns into more stylish options?

After an extensive search, I was only able to locate one solution at this link. I scoured the entire internet for alternatives. ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Insert a new item into an existing list using jQuery

I am looking to enhance user experience by allowing them to easily add multiple sets of inputs with just one click. I have been experimenting with jQuery in order to dynamically insert a new row of input fields after the initial set. My current approach i ...

Using various functions for event listeners

Avoiding jQuery Hello there! I'm currently working on implementing multiple Event Listeners for a button. function logoContame(){ var logo = document.getElementById("logoheader"); logo.addEventListener("click", hideDivHistorias) ...

Enhancing the D3.js chart with tooltip, x-axis, and y-axis titles

I am looking to enhance the graph by adding a tooltip that displays information on the Y-axis value, time to the circle, and titles for both the X-axis and Y-axis. I attempted to implement this functionality within svg.selectAll but encountered difficultie ...