1

我正在尝试在我的项目中包含文件上传这是我的 html 部分

 <form ng-app="fileUpload" ng-controller="MyCtrl as up"     name="up.upload_form">
        Single Image with validations
    <input 
        type="file" 
        ngf-select 
        ng-model="up.file" 
        name="file" 
        ngf-pattern="'image/*'"
        accept="image/*" 
        ngf-max-size="20MB" 
        />
    Image thumbnail: <img style="width:100px;" ng-show="!!up.file" ngf-thumbnail="up.file || '/thumb.jpg'"/>
    <i ng-show="up.upload_form.file.$error.required">*required</i><br>
    <i ng-show="up.upload_form.file.$error.maxSize">File too large 
    {{up.file.size / 1000000|number:1}}MB: max 20M</i>
   <!--  Multiple files
    <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div>
    Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> -->
    <button type="submit" ng-click="up.submit()">submit</button>
    <p>{{up.progress}}</p>
</form>

我的控制器是

angular.module('fileUpload', ['ngFileUpload'])
.controller('MyCtrl',function(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
        vm.upload(vm.file); //call upload function
    }
};

vm.upload = function (file) {
    Upload.upload({
        url: 'http://localhost:3000/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. Response: ');
        } 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
    });
};
});

文件上传 html 在我的主模块 myApp 中

<body ng-app="myApp" ng-controller="MyController">

当我运行文件时,文件上传控制器显示错误 http://errors.angularjs.org/1.5.0-beta.2/ng/areq?p0=MyCtrl&p1=not%20aNaNunction%2C%20got%20undefined at Error (本国的)

提前致谢

4

1 回答 1

0

ng-app如果您希望这些控制器成为同一应用程序的一部分,则不应在同一页面上有另一个声明 - 删除它ng-app="fileUpload"。然后,您的 HTML 中将具有如下结构:

<body ng-app="myApp" ng-controller="MyController">
  ..
  <form ng-controller="MyCtrl as up"name="up.upload_form">
  ..
  </form>
  ..
</body>

所以你可以从using调用MyController函数,在这里阅读更多:AngularJS access parent scope from child controllerMyCtrl$scope.$parent

于 2016-02-20T14:41:42.840 回答