Auto populate input based on file name with AngularJS
- by LouieV
I am playing around with AngularJS and have not been able to solve this problem. I have a view that has a form to upload a file to a node server. So far I have manage to do this using some directives and a service. I allow the user to send a custom name to the POST data if they desire. What I wan to accomplish is that when the user selects a file the filename models auto populates.
My view looks like:
<div>
<input file-model="phpFile" type="file">
<input name="filename" type="text" ng-model="filename">
<button ng-click="send()">send</button>
</div>
file-model is my directive that allows the file to be assigned to a scope.
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]);
});
});
}
}]);
The service:
myApp.service('fileUpload', ['$http', function($http){
this.uploadFileToUrl = function(file, uploadUrl, optionals) {
var fd = new FormData();
fd.append('file', file);
for (var key in file) {
fd.append(key, file[key]);
}
for(var i = 0; i < optionals.length; i++){
fd.append(optionals[i].name, optionals[i].data);
}
});
}]);
Here as you can see I pass the file, append its properties, and append any optional properties.
In the controller is where I am having the troubles. I have tried $watch and using the file-model but I get the same error either way.
myApp.controller('AddCtrl', function($scope, $location, PEberry, fileUpload){
//$scope.$watch(function() {
// return $scope.phpFile;
//},function(newValue, oldValue) {
// $scope.filename = $scope.phpFile.name;
//}, true);
// if ($scope.phpFiles) {
// $scope.filename = $scope.phpFiles.name;
// }
$scope.send = function() {
var uploadUrl = "/files";
var file = $scope.phpFile;
//var opts = [{ name: "uname", data: file.name }]
fileUpload.uploadFileToUrl(file, uploadUrl);
};
});
Thank you for your help!