0
我有兩個類似的指令,我想運行特定文件的驗證器(這不是最佳實踐,我知道,因爲它不是基於DRY原則,但我只是學習AngularJS)。錯誤的函數在AngularJS指令中調用
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>
第二個按鈕應該驗證正確json
格式,但不是有效的JSON的,有效的圖像指令的函數被調用,並針對jpg
驗證。
handleImageFile和handleJsonFile函數只讀取文件。
我錯過了什麼?
避免使用'.change' - 使用手錶。 –