I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes.
module.js
var $moduleExample = angular.module("$moduleExample", ["ngMaterial"]);
$moduleExample.controller("testController", [
"$scope",
function (
$scope,
) {
$scope.fileDialog = function () {
var el = angular.element("#file-dialog");
el.trigger('click');
};
}
]);
$moduleExample.directive("validJson", function jsonValidFile() {
var validFormats = ['json'];
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
elem.on('change', function () {
var value = elem.val(),
ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
scope.isModelValid = validFormats.indexOf(ext) !== -1;
});
}
};
});
$moduleExample.directive("validImage", function imageValidFile() {
var validFormats = ['jpg'];
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
elem.on('change', function () {
var value = elem.val(),
imageValue = attrs.validImage,
ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
scope.isImageValid = validFormats.indexOf(ext) !== -1;
});
}
};
});
template.html
<div>
<md-button ng-click="fileDialog();">
<md-icon md-font-set="material-icons">file_upload</md-icon>
upload json
</md-button>
<input id="file-dialog" type="file" class="ng-hide" valid-image on-file-change="handleImageFile" ng-model="image" />
</div>
<div>
<md-button ng-click="fileDialog();">
<md-icon md-font-set="material-icons">file_upload</md-icon>
upload image
</md-button>
<input id="file-dialog" type="file" class="ng-hide" valid-json on-file-change="handleJsonFile" ng-model="model" />
</div>
The issue arises when the second button is clicked to validate the proper json
format, but instead of applying the valid-json directive, it triggers the valid-image directive and validates against jpg
.
Both handleImageFile and handleJsonFile functions are only focused on reading the files.
What could be causing this discrepancy?