Skip to content

Instantly share code, notes, and snippets.

@marciejones
Forked from cvan/prefill-url.js
Last active June 19, 2017 14:07
Show Gist options
  • Save marciejones/302321c5ce9f128cb174df70ec48eb32 to your computer and use it in GitHub Desktop.
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
// 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