Javascript AngularJS指令中调用了错误的函数
我有两个类似的指令,我想为特定文件运行验证器(我知道这不是最佳实践,因为它不是基于DRY原则。但我只是在学习AngularJS)Javascript AngularJS指令中调用了错误的函数,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有两个类似的指令,我想为特定文件运行验证器(我知道这不是最佳实践,因为它不是基于DRY原则。但我只是在学习AngularJS) module.js var $moduleExample = angular.module("$moduleExample", ["ngMaterial"]); $moduleExample.controller("testController", [ "$scope", function ( $scope, ) {
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
格式,但不是有效的json,而是调用valid image指令的函数并根据jpg
进行验证
handleImageFile和handleJsonFile函数仅读取文件
我缺少什么?在fileDialog函数中,我提到了file dialog元素。因为我在两个指令上都有相同的标识符和函数,所以造成了混淆。避免使用
。更改-使用watch。