将 ng-change 应用于已经使用自己的指令的<输入类型="文件"..>



我想在每次输入类型'file'更改时调用validateFormat()函数。注意,自定义指令是使用'file-model'

如果我尝试添加'ng-change="validateFormat()' '作为输入,控制台打印如下错误:no controller: ngModel。

如何将此元素绑定到ng-change?

<div ng-controller="MyControllerController">
    <input type="file" file-model="file" />
    <button ng-click="uploadFile()">Upload</button>
    {{error}}
</div>

角1. x :

var module = angular.module("umbraco");
module.controller('OnlineServices.JobCentreUploadController', [
                  '$scope', 'fileUpload', function($scope,         
$scope.uploadFile = function () {
      var file = $scope.file;
      var uploadUrl = "/umbraco/api/jc/Upload";
      fileUpload.uploadFileToUrl(file, uploadUrl, $scope);
    };
}]);
module.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;
        element.bind('change', function () {
            scope.$apply(function () {
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);
module.service('fileUpload', ['$http', 'notificationsService', function ($http, notificationsService) {
this.uploadFileToUrl = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    })
    .success(function () {
        notificationsService.success("Success", "File uploaded successfully.");
    })
    .error(function () {
        notificationsService.error("Error", "File has not been uploaded.");
    });
}
}]);

ng-change指令需要ng-model屏后ng-change为对应ng-model设表

来解决您的问题,您试图调用ng-change而没有指定ng-model,这是错误的原因。

在你的自定义指令中,你为change事件创建了一个事件处理程序。

所以如果你想为你的输入元素设置ng-change事件,你可以在你的自定义指令中做,而不需要去ng-change指令。

为了做到这一点,你需要将validateFormat函数作为参数传递给自定义指令,并在change回调中执行函数,如下所示:

示例代码:

element.bind('change', function () {
    scope.$apply(function () {
        modelSetter(scope, element[0].files[0]);
    });
    //Get this function using isolated scope and call it
    validateFormat();
});

最新更新