2015-09-20 79 views
1

我似乎无法从上传文件中获取文本字符串。之前它在我的控制器中工作。不知何故,它停止工作,console.log($ scope.importFile)显示'未定义'。我对处理文件上传和angularjs都很陌生。你能帮助指出哪里出了问题吗?angularjs FileReader返回undefined

我的指令,并控制和HTML:

app.directive('fileReader', function() { 
 
    return { 
 
    scope: { 
 
     fileReader:"=" 
 
    }, 
 
    link: function(scope, element) { 
 
     $(element).on('change', function(changeEvent) { 
 
     var files = changeEvent.target.files; 
 
     //console.log(files.length); 
 
     
 
     if (files.length) { 
 
      var r = new FileReader(); 
 
      r.onload = function(e) { 
 
       var contents = e.target.result; 
 
       scope.$apply(function() { 
 
       scope.fileReader = contents; 
 
       }); 
 
       //console.log(scope.fileReader + ' in onload'); 
 
       //r.readAsText(files[0]); 
 
      }; 
 
      console.log('using file-reader directive'); 
 
      console.log(r.readAsText(files[0])); 
 
      r.readAsText(files[0]); 
 
     } 
 
     }); 
 
    } 
 
    }; 
 
}); 
 

 

 

 
app.controller('NavController', function($scope, $location, $modal, toaster) { 
 
    
 
    $scope.selectFile = function() { 
 
     console.log('print upload: '+ $scope.importFile); 
 
     alert('print upload: '+ $scope.importFile); 
 
    }; 
 
};
<div class="form-group">    
 
    <input type="file" file-reader="importFile" class="form-control"/><br>  
 
</div>  
 
    
 
<div class="form-group"> 
 
<label> 
 
    <input class="pull-left text-left col-sm-1 control-label" type="checkbox" ng-model="confirmDeleteMode"> 
 
    <span class="glyphicon glyphicon-trash col-sm-10 pull-left text-left"> 
 
     <em style="color:red">By checking this box, I understand....</em> 
 
    </span> 
 
    </label> 
 
</div> 
 
      
 
<div class="form-group">  
 
    <input type="button" value="Upload File" class="btn btn-inverse" ng-click="selectFile()" ng-disabled="!confirmDeleteMode"> 
 
      
 
    <button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button> 
 
</div>

回答

0

那么首先,你必须在你的JavaScript

app.controller('NavController', function($scope, $location, $modal, toaster) { 

    $scope.selectFile = function() { 
     console.log('print upload: '+ $scope.importFile); 
     alert('print upload: '+ $scope.importFile); 
    }; 
}; 

最后一行语法错误在哪里你忘了关闭括号。 JavaScript控制台应该通知你。

app.controller('NavController', function($scope, $location, $modal, toaster) { 

    $scope.selectFile = function() { 
     console.log('print upload: '+ $scope.importFile); 
     alert('print upload: '+ $scope.importFile); 
    }; 
}); // <- Here 

其次,尽管没关系,$(element)是多余的。 AngularJS提供了一个严格精简的实现,它模仿称为jqLit​​e的jQuery。见here。这很像jQuery,但不是真的。 (即使在支持的功能中,实际上也存在显着的行为差异,所以要小心)。由AngularJS给出的所有元素已经包装在jqLit​​e中。此外,如果你真的想要jQuery,只需在AngularJS和AngularJS之前导入jQuery,然后使用jQuery而不是它的jqLit​​e。所以这里element已经包装在jQuery中。另一个值得警惕的词语是,AngularJS 2.0将完全变为drop the whole jqLite thing,因为现在的DOM已经足够强大了。

否则它工作正常。见Fiddle

+0

非常感谢它 –