Skip to content

Instantly share code, notes, and snippets.

@TheWass
Last active September 30, 2016 14:28
Show Gist options
  • Save TheWass/0da0aa38e47352c8b3c982a89ca6414d to your computer and use it in GitHub Desktop.
Save TheWass/0da0aa38e47352c8b3c982a89ca6414d to your computer and use it in GitHub Desktop.
Custom AngularJS modules
angular.module('twFilters', [])
.filter('unique', function () {
return function (arr, field) {
var o = {}, i, l = (arr) ? arr.length : 0, r = [];
for (i = 0; i < l; i += 1) {
o[arr[i][field]] = arr[i];
}
for (i in o) {
r.push(o[i]);
}
return r;
};
})
.filter('alphabetize', function () {
return function (arr, field) {
if (arr && typeof arr.sort === "function") {
return arr.sort(function (a, b) {
if (field)
return a[field].toString().localeCompare(b[field].toString());
else
return a.toString().localeCompare(b.toString());
});
} else {
//unsortable
return arr;
}
};
})
.filter('join', function () {
return function (arr, delim) {
if (arr && typeof arr.join === "function") {
return arr.join(delim)
} else {
//unjoinable
return arr;
}
};
})
.filter('getprop', function () {
return function (arr, field) {
if (field && Array.isArray(arr) && typeof arr[0] === "object") {
return arr.map(function (item) {
if (item.hasOwnProperty(field))
return item[field];
else
return item;
});
} else {
// has no props. :(
return arr;
}
};
});
angular.module('twValidators', [])
.directive('integer', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$validators.integer = function (modelValue, viewValue) {
//Empty controls are valid
if (ctrl.$isEmpty(modelValue)) return true;
// REGEX for integers
return /^\-?\d+$/.test(viewValue);
};
}
};
})
.directive('nChars', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var numDigits = attrs.nChars;
ctrl.$validators.nChars = function (modelValue, viewValue) {
//Empty controls are valid
if (ctrl.$isEmpty(modelValue)) return true;
return viewValue.length == numDigits;
};
}
};
})
.directive('decimal', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$validators.decimal = function (modelValue, viewValue) {
//Empty controls are valid
if (ctrl.$isEmpty(modelValue)) return true;
return /^\d+\.\d+$/.test(viewValue);
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment