3

I am new to AngularJs and am currently working on creating a file upload script. I searched the web and combined a few scripts to achieve the code below.

My problem is that the clear button should clear the filename on click and remove the file from the queue.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>   

</head>

<body ng-app = "myApp">

  <div ng-controller = "myCtrl">

     <input type = "file" file-model = "myFile" file-select="file"/>

    <button ng-click="clear()">clear</button>
     <button ng-click = "uploadFile()">upload me</button>
  </div>

  <script>
     var app = angular.module('myApp', []);

     app.controller('myCtrl', ['$scope', 'fileUpload', 'fileSelect', function($scope, fileUpload, fileSelect){
        $scope.uploadFile = function(){
           var file = $scope.myFile;

           console.log('file is ' );
           console.dir(file);

           var uploadUrl = "/fileUpload";
           fileUpload.uploadFileToUrl(file, uploadUrl);
        };

            $scope.clear = function() {
            $scope.file = null;
            };
        }]);

     app.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]);
                 });
              });
           }

        };
     }]);

    app.directive('fileSelect', function() {

            return function( scope, elem, attrs ) {
                var selector = $parse(attrs.fileSelect);
                var modelSelector = elem.append(selector);

                selector.bind('change', function( event ) {
                    scope.$apply(function() {
                        scope[ attrs.fileSelect ] = event.originalEvent.target.files;
                    });
                });
                scope.$watch(attrs.fileSelect, function(file) {
                selector.val(file);
                });
            };
    });

     app.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, uploadUrl){
           var fd = new FormData();
           fd.append('file', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })

           .success(function(){
           })

           .error(function(){
           });
        }
     }]);



   </script>

 </body>
</html>
4
  • try $scope.file = ""; in clear() Commented Jun 15, 2016 at 11:46
  • @TirthrajBarot this doesnt work, i already tried it. Commented Jun 15, 2016 at 11:48
  • what error does it show in the console? Commented Jun 15, 2016 at 11:51
  • I tried building a plunker with your code but got a series of errors in the console just on startup. For instance, 'fileSelect' uses $parse but you haven't injected it. Another "selector.val is not a function". I'd make sure you resolve any startup errors before trying to solve this specific issue Commented Jun 15, 2016 at 12:07

2 Answers 2

1

clear function should be defined as below

$scope.clear = function () {
    angular.element("input[type='file']").val(null);
};

Check the snippet below.

var app = angular.module('myApp', []);

	app.controller('myCtrl', ['$scope', function($scope){
		$scope.uploadFile = function(){
			var file = $scope.myFile;

			console.log('file is ' );
			console.dir(file);

			var uploadUrl = "/fileUpload";
			fileUpload.uploadFileToUrl(file, uploadUrl);
		};

		$scope.clear = function () {
			angular.element("input[type='file']").val(null);
		};

	}]);
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app = "myApp">

	<div ng-controller = "myCtrl">

		<input type = "file" ng-model = "myFile" file-select="file"/>

		<button ng-click="clear()">clear</button>
	</div>
  </body>

Sign up to request clarification or add additional context in comments.

4 Comments

what worked for me was $scope.file = null; in the clear(); Thanks for your help though. It guided me in the right direction.
yes that works well Nirbhay.. That would have been my first answer ... but when you use any directive with it, that won't work.. @NirbhayTandon
But still i would be happy if you could mark me correct &or vote me up for this answer... @NirbhayTandon
You got 2 voteups from me! You deserved that! @NirbhayTandon
1

I was able to solve it myself. Added one more function too.

<body>
<div ng-controller="MainCtrl" >

<table class="table table-bordered" cellspacing="1" cellpadding="2"
        rules="all" border="0" id="gridSwipeApp" >

    <tr style="background-color: #009ca6; color: white;" ng-repeat="item in items"><a ng-click="getId(item)">
    {{item.content}}
    </a>
        <td>
            <div file-select="file" file-model="myFile"></div></td>

        <td><button ng-click="clear($index)" ng-model="activeItem.clear">clear</button></td>
        <td><button ng-click="uploadFile()" ng-model="activeItem.uploadFile"> Upload</button></td>
    </tr>
    </table>
<button type="button" ng-click="addMore()">Add More</button>


</div>
<script>
  var app = angular.module('myApp', []);
  var template = '<input type="file" name="files"/>'; 

  app.controller('MainCtrl', function($scope) {
 $scope.items=[{
    id: 1,
    myFile: 'item1',
    clear: 'clearButton1',
    uploadFile: 'uploadbutton1',
}];

$scope.activeItem = {
        myFile: '',
        clear: '',
        uploadFile: '',
}

$scope.addMore = function(){
    $scope.activeItem.id = $scope.items.length + 1;
    $scope.items.push($scope.activeItem);
    $scope.activeItem ={}

}

$scope.file = null;
$scope.clear = function(index) {
    $scope.items.splice(index,1);
    $scope.file = null;
 };
});

app.directive('fileSelect', function() {

return function( scope, elem, attrs ) {
var selector = $( template );
elem.append(selector);
selector.bind('change', function( event ) {
  scope.$apply(function() {
    scope[ attrs.fileSelect ] = event.originalEvent.target.files;
   });
 });
 scope.$watch(attrs.fileSelect, function(file) {
  selector.val(file);
  });
 };
});

app.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]);
         });
      });
   }

 };
}]);

app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
   var fd = new FormData();
   fd.append('file', file);

   $http.post(uploadUrl, fd, {
      transformRequest: angular.identity,
      headers: {'Content-Type': undefined}
   })

   .success(function(){
   })

   .error(function(){
   });
  }
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.