文件-在AngularJS中上传文件时由于data-ng-if而未定义 [英] File - undefined due to data-ng-if while uploading file in AngularJS

查看:95
本文介绍了文件-在AngularJS中上传文件时由于data-ng-if而未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularJs 1.3进行文件上传 我遇到的情况是控制器可以访问文件而不在标签中添加data-ng-if,但是如果我包含data-ng-if,则在控制器中的文件未定义的情况下,任何人都可以帮助我了解更多有关此问题的信息,并且一种可以在上传文件时使用data-ng-if的解决方案

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

}]);

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

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

推荐答案

ng-if为"form-group" div中的dom元素创建了一个新作用域. 改用ng-show

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

这篇关于文件-在AngularJS中上传文件时由于data-ng-if而未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆