文件 - 由于在AngularJS中上传文件时数据-ng-if而未定义

时间:2015-04-15 12:26:42

标签: angularjs file upload undefined

我正在使用angularJs 1.3处理文件上传 我有一种情况,控制器可以在标签中没有data-ng-if的情况下访问文件,但是如果我包含数据-ng-如果控制器中的文件未定义,任何人都可以帮助我理解有关该问题的更多信息,以及我可以在上传文件时使用data-ng-if的解决方案

<div ng-controller = "QuestionsListController">
    <form id="questionForm" enctype="multipart/form-data" method="post" data-ng-submit="uploadForm()">
        <p>
            <div class="form-group" data-ng-if="isTestQuestion">
                <input type="file" file-model="myFile"/>
            </div>
        </p>        
        <button type="submit">upload me</button>
    </form>
</div>

包含控制器和服务以及指令

的脚本
myApp.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]);
                });
            });
        }
    };
}]);

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileAndFieldsToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            console.log("success : ",data);
        })
        .error(function(){
            console.log("fail");
        });
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    $scope.uploadForm = function(){
        var file = $scope.myFile;
        console.log('file is ' + JSON.stringify(file));
        var uploadUrl = 'http://localhost:8080/ajax/recruiter/codingQuestion';
        fileUpload.uploadFileAndFieldsToUrl(file, uploadUrl);
    };

}]);

我可以使用console.log()查看指令中的文件 提前致谢。 :)

1 个答案:

答案 0 :(得分:1)

ng-if为'form-group'div中的dom元素创建一个新范围。 请改用ng-show