-
-
Save marciejones/302321c5ce9f128cb174df70ec48eb32 to your computer and use it in GitHub Desktop.
prefill `input[type=url]` field with "http://" upon focus using an angular directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prefill URL field with 'http://' upon focus. | |
<label class="item item-input" ng-if="vm.website === undefined || !vm.api && !vm.account"> | |
<input id="website" name="website" type="url" placeholder="What is your choir/chorus website?" | |
ng-model="vm.website" required http-prefix> | |
var app = angular.module('APPNAME'); | |
app.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); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment