4

I have requirement like this.

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

I have the HTML code like this. Once the user enter text in website URL field I need to add prefix to the URL with http://.

If the user is entering the URL with http://. then no need add the http:// prefix.

How can i do with in AngularJS .

Please suggest

3
  • should the model contain the http:// or just your output?CommentedDec 16, 2015 at 8:59
  • Try using or creating a filter that handles all the regex checks and returns the url as you wish
    – Synapse
    CommentedDec 16, 2015 at 8:59
  • whenever you are getting your output text you can easily append know ?
    – vinodh
    CommentedDec 16, 2015 at 9:04

1 Answer 1

2

Ok, there is also another possibility to use a formater and parser to complete the task at the model level. I put the code in here from another solution, since the code there is hosted external:

https://stackoverflow.com/a/19482887/3641016

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) { // Need to add prefix if we don't have http:// prefix already AND we don't have part of it 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>

2
  • 1
    Thank you for your reply.In my case I need to add http:// to the input filed when the user start to type on input filed. is it possible??
    – Kichu
    CommentedDec 16, 2015 at 9:20
  • 1
    @Kichu ther is this possibility. have a look at the improved answerCommentedDec 16, 2015 at 9:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.