File - undefined due to data-ng-if while uploading file in AngularJS

徘徊边缘 提交于 2019-12-08 12:37:20

问题


I am working with file upload using the angularJs 1.3 I have a situation where the controller can access the file without the data-ng-if in the tag, but if I include the data-ng-if the file in the controller is undefined can anyone help me understand more about the issue, and a solution that I can use data-ng-if while uploading the file

<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>

the script that contains controller and service and directive

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);
    };

}]);

I can see the file in the directive using the console.log() thanks in advance. :)


回答1:


The ng-if creates a new scope for the dom elements within the 'form-group' div. Use ng-show instead



来源:https://stackoverflow.com/questions/29650191/file-undefined-due-to-data-ng-if-while-uploading-file-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!