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