Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. module.directive('colorValidate', function() {
  2. return {
  3. restrict: 'A',
  4. scope: {
  5. color: '=ngModel'
  6. },
  7. link: function(scope, element) {
  8. var previousValue = '#ffffff';
  9. //pattern that accept #ff0000 or #f00
  10. var colorPattern = new RegExp('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$');
  11. element.on('focus', function() {
  12. previousValue = scope.color;
  13. });
  14. element.on('blur', function() {
  15. if (!colorPattern.test(scope.color)) {
  16. scope.$apply(function() {
  17. scope.color = previousValue;
  18. });
  19. }
  20. else {
  21. scope.$apply(function() {
  22. scope.color = scope.color.toLowerCase();
  23. });
  24. }
  25. });
  26. }
  27. };
  28. });
  29.  
  30. <input color-validate type="text" ng-model="color.color"/>
  31.  
  32. describe('colorValidate directive', function() {
  33. var scope,
  34. elem,
  35. compiled,
  36. html;
  37.  
  38. beforeEach(function() {
  39. html = '<input color-validate type="text" ng-model="color.color"/>';
  40.  
  41. inject(function($compile, $rootScope) {
  42. scope = $rootScope.$new();
  43. scope.color = {color: '#aaaaaa'};
  44. elem = angular.element(html);
  45. compiled = $compile(elem);
  46. compiled(scope);
  47. scope.$digest();
  48. });
  49. });
  50.  
  51. it('should permit valid 6-chars color value', function() {
  52. elem.focus();
  53. elem.val('#FF0000');
  54. elem.blur();
  55. scope.$digest();
  56. expect(elem.val()).toBe('#FF0000');
  57. });
  58.  
  59. it('should reject non valid color values', function() {
  60. elem.focus();
  61. elem.val('#F00F');
  62. scope.$digest();
  63. elem.blur();
  64. expect(elem.val()).toBe('#aaaaaa');
  65. });
  66. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement