Skip to content

Instantly share code, notes, and snippets.

@muratsplat
Last active August 29, 2015 14:15
Show Gist options
  • Save muratsplat/b98b23919d4125f2b72b to your computer and use it in GitHub Desktop.
Save muratsplat/b98b23919d4125f2b72b to your computer and use it in GitHub Desktop.
HttpPrefix Directive with test For Angular, This directive make force user to entry 'http://' on input element
'use strict';
/**
* @ngdoc directive
* @name boruu.directive:httpPrefix
* @description
* # httpPrefix
*/
angular.module('yourApp')
.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) === -1) {
controller.$setViewValue('http://' + value);
controller.$render();
return 'http://' + value;
}
return value;
}
controller.$formatters.push(ensureHttpPrefix);
controller.$parsers.splice(0, 0, ensureHttpPrefix);
}
};
});
// Test with Karma
'use strict';
describe('Directive: httpPrefix', function () {
// load the directive's module
beforeEach(module('yourApp'));
var element, scope, directive;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
scope.url = 'dooo'
}));
it('should make hidden element visible', inject(function ($compile) {
element = '<input name="test" ng-model="url" http-prefix>';
directive = $compile(element)(scope);
scope.$digest();
expect(scope.url).toMatch('http://doo');
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment