I've written a directive to validate the width and height of an image in AngularJS. I'm not a JS genius but I get along with it. So I would appreciate some feedback on this directives code if this can be done better in the context of Angular and the JS language itself.
angular.module('app').directive('imageFileValidator', ['fileReader', function (fileReader) {
return {
restrict: 'A',
require: '^ngModel',
link: function ($scope, el, attr, ctrl) {
// Binds the change callback for the element
el.bind('change', function (e) {
var file = ((e.srcElement || e.target).files[0]);
fileReader.getImageSize(file, $scope).then(function(result) {
var imageSize = result;
if (attr.validateHeight != undefined) {
var heightRule = attr.validateHeight.split(' ');
var validHeight = validateImageSize(imageSize.height, heightRule[0], heightRule[1]);
ctrl.$setValidity('imageSizeY', validHeight);
}
if (attr.validateWidth != undefined) {
var widthRule = attr.validateWidth.split(' ');
var validWidth = validateImageSize(imageSize.width, widthRule[0], widthRule[1]);
ctrl.$setValidity('imageSizeX', validWidth);
}
});
var validateImageSize = function(value1, operator, value2) {
if (operator == '==') {
return (value1 == value2);
}
if (operator == '>=') {
return (value1 >= value2);
}
if (operator == '>') {
return (value1 > value2);
}
if (operator == '<=') {
return (value1 <= value2);
}
if (operator == '<') {
return (value1 < value2);
}
throw 'Invalid operator ' + operator + ' !';
};
});
}
}
}]);