Utilize AngularJS to append a prefix value to an input field

My current requirement involves the following:

<label>Website Address</label>
                    <span><input type="text" class="form-factor" data-ng-model="websiteUrl"/></span>

Currently, I have HTML code that looks like this. When a user enters text in the website URL field, I want to automatically add a prefix of http:// to the URL.

If the user includes http:// in the URL they enter, then I do not want to add it again.

How can I achieve this using AngularJS?

Please provide your suggestions

Answer №1

Alright, here's another approach you can take to accomplish this task at the model level using a formatter and parser. I've included the code snippet below from a different source since it's hosted externally:

angular.module('app', [])
  .controller('testCtrl', function($scope) {
    $scope.input1 = "";
    $scope.input2 = "";
  })
  .filter('prefixHttp', function() {
    return function(input) {
      return input.indexOf("http://") == 0 ? input : 'http://' + input;
    };
  })
  .directive('httpPrefix', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, controller) {
        function ensureHttpPrefix(value) {
          // Add prefix if no http:// prefix already present
          if (value && !/^(https?):\/\//i.test(value) && 'http://'.indexOf(value) !== 0 && 'https://'.indexOf(value) !== 0) {
            controller.$setViewValue('http://' + value);
            controller.$render();
            return 'http://' + value;
          } else
            return value;
        }
        controller.$formatters.push(ensureHttpPrefix);
        controller.$parsers.splice(0, 0, ensureHttpPrefix);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="testCtrl">
  <label>prefix the output
    <input ng-model="input1" />{{input1 | prefixHttp}}
  </label>
  <br/>

  <label>prefix the model
    <input ng-model="input2" http-prefix/>{{input2}}
  </label>
</div>

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

Creating visually appealing Highcharts.js visualizations for both mobile and desktop devices

Has anyone had success implementing a responsive design with Highcharts to ensure charts look great on both mobile and desktop screens? By default, Highcharts do adjust when resizing the browser window, but sometimes the X-axis can become cluttered by tic ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

Here is a guide on updating HTML table values in Node.js using Socket.IO

I successfully set up socket io communication between my Node.js backend and HTML frontend. After starting the Node.js server, I use the following code to emit the data 'dRealValue' to the client side: socket.emit ('last0', dRealValue) ...

Is it better to have dynamic application loading in Angular+MVC or opt for two separate applications?

Looking for assistance with structuring my AngularJs project within an ASP.NET MVC + Web API application. Essentially, the ASP.NET MVC portion consists of a landing page and authentication pages, which then redirect to the main application in Index.cshtml. ...

Exploring the ancestry of Mongo

I am currently working on constructing a family tree that can have an infinite number of levels for parents and children. I am also interested in finding relationships like brothers, sisters, cousins, and so on. However, I'm facing some confusion when ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

What mechanisms do frameworks use to update the Document Object Model (DOM) without relying on a

After delving into the intricate workings of React's virtual DOM, I have come to comprehend a few key points: The virtual DOM maintains an in-memory representation of the actual DOM at all times When changes occur within the application or compo ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

Retrieving data from the database without the need to reload the page

Hi there! I have a PHP script that fetches data from a database and I want to display this data within a div element with a "link" class without having to reload the page. Check out the code snippet below: <? include('config.php'); $rs = m ...

ag-grid's onGridReady function is not functioning properly

I am trying to dynamically load ag-grid when a button is clicked, but I have encountered issues with both of my approaches. Here is my code for the first method: onBtnClick(){ this.gridOptions ={ onGridReady : function(){ console ...

Is there a way to prevent Mac users from using the back and refresh buttons on their browser?

There seems to be a common trend of disabling the back button or refresh button on Windows using JS or Jquery to prevent F5 from working. Can this same method be applied to CMD+R on Mac computers? ...

Utilizing JSON File as an Array in a Node.JS Environment

I'm struggling with converting a .json file into an array object using NodeJS, Here's the JSON content: { "cat": { "nani": "meow" }, "dog": { "nani": "woof" } } index.js: const array = require('../../data/use ...

Sorting by price using the ng-repeat directive is not suitable for this

Utilizing angular's ng-repeat along with orderBy on a product catalog page to sort the products based on a select change. The ordering by name using orderBy works as expected, however, when it comes to price it sorts like this: 1,10,11,12,13,14,2,3,4 ...

What is the best way to slice text in JavaScript?

Looking to remove the ".00" from the class ".woocommerce-Price-amount" with Javascript. The amount should have a space at the end. <div class="elementor-shortcode"> Free shipping from <span class="woocommerce-Price-amount amount"> ...

Guide on utilizing Three.js OrbitControl with several objects

I managed to get the orbit control feature working, but I am facing an issue where controlling one object also ends up controlling all three objects on the page. Additionally, pan/zoom functionality does not seem to work at all with the OrthographicCamera. ...

Engage with elements enhanced by jQuery functionality

Here's a simple example: <div id="test">add more text</div> Clicking on the above text triggers this code: jQuery('#test').on('click', function (event) { $('body').append("<div id='newtest' ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Incorporate a variable into a function by integrating it

I'm struggling to accurately calculate the total hours needed based on the method of transportation. This code represents my initial attempt at learning how to code, diving into JavaScript for the first time. Here's my script: $(document).read ...