Angular update model from directive
HTML
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="App">
<div ng-controller="Ctrl" ng-init="init()">
<form name="myForm">
<input type="url" name="field1" ng-model="field1" http-prefix>
{{field1}}
</form>
</div>
</div>
JavaScript
var app = angular.module('App', []);
function Ctrl($scope) {
$scope.init = function() {
$scope.field1 = "dummy";
}
}
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);
}
};
});