angular.js:ReferenceError:up未定义

时间:2016-04-22 16:53:52

标签: javascript angularjs file-upload

我正在为我的项目上传功能,我的按钮包括上传和提交功能。一旦我点击上传,我在开发者控制台中收到错误:

  

angular.js:13236 ReferenceError:未定义向上

关于这个错误的引用说明了这行中的问题

$scope.$watch("up.file", function() { if (up.file) up.submit() });

完全在if (up.file),但与此同时,一切正常。上传功能有效,所有文件都在上传。所以如果有人能解释我的错误,我感激不尽?

  app.controller('uploadCtrl',['$scope', '$http','Upload','$window',function($scope, $http,Upload,$window){
    var vm = this;
    vm.submit = function(){ //function to call on form submit
        if (vm.upload_form.file.$valid && vm.file) {//check if from is valid

            //console.log(vm.file.name);
            vm.upload(vm.file); //call upload function
            //vm.file.name = prompt("put you name");
        }
        $scope.$watch("up.file", function() { if (up.file) up.submit() });
    };

    vm.upload = function (file) {
        Upload.upload({
            url: '/upload', //webAPI exposed to upload the file
            data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
                $window.alert('Success ' + resp.config.data.file.name + ' uploaded.');
            } else {
                $window.alert('an error occured');
            }
        }, function (resp) { //catch error
            console.log('Error status: ' + resp.status);
            $window.alert('Error status: ' + resp.status);
        }, function (evt) {
            console.log(evt);
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
            setTimeout(10000);
        }).then (function() {
            $http.get('/compare').success(function() {
                setTimeout(function() { alert("success!"); }, 5000);
                // url was called successfully, do something
                // maybe indicate in the UI that the batch file is
                // executed...
            });
        });
    };
}]);

1 个答案:

答案 0 :(得分:1)

up变量未在您的控制器中定义。相反,vm已定义。

因此,请使用vm.filevm.submit

修改: 您正在watch方法中定义submit表达式,并且您正在从submit表达式调用watch方法。

您应该在watch方法之外定义submit,如下所示:

    vm.submit = function(){ //function to call on form submit
        if (vm.upload_form.file.$valid && vm.file) {//check if from is valid

            //console.log(vm.file.name);
            vm.upload(vm.file); //call upload function
            //vm.file.name = prompt("put you name");
        }
    };

    $scope.$watch("vm.file", function() { if (vm.file) vm.submit() });