Angular update model from directive

by TheoI

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
                var term = '£$'
                if (value.length < term.length) {
                    controller.$setViewValue(term);
                    controller.$render();
                    return term;
                }
                else if(value.indexOf(term) !== 0) {
                    controller.$setViewValue(term + value);
                    controller.$render();
                    return term + value;
                }
                else
                    return value;
            }
            controller.$formatters.push(ensureHttpPrefix);
            controller.$parsers.splice(0, 0, ensureHttpPrefix);
        }
    };
});