1

here is directive.

 app.directive("fileInput", function($parse){  
  return{  
       link: function($scope, element, attrs){  
            element.on("change", function(event){  
                 var files = event.target.files;  
                 $parse(attrs.fileInput).assign($scope, element[0].files); 
                console.log(element[0].files);//this shows file
                 $scope.$apply();  
            });  
       }  
  }
});

HTML part:

<input class="inputFile"  type="file" id="files" file-input="files">
<button type="button" ng-click="uploadFile();">Submit</button>

Controller function:

$scope.uploadFile = function(){  
        console.log($scope.files);//this is undefined
        if(!$scope.files){
            alert("select file");//prog is getting stuck here
        }else{/*some code*/}  

$scope and every dependency is defined is controller, still not getting file. please tell me where i am doing wrong because same code is running in other modules.

uploadFile();

lies under some child controller..

mahipal singh
  • 355
  • 3
  • 15
  • 1
    It works in this [DEMO on PLNKR](http://plnkr.co/edit/AW1cNLOamFtPt0PylOr2?p=preview). There is some other problem. Is the `file-input` directive inside an `ng-repeat? In that case there would be a data hiding problem. See [What are the nuances of scope prototypal / prototypical inheritance in AngularJS?](https://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs). – georgeawg Jun 13 '18 at 19:39
  • In a comment in an answer below, you mention that the `uploadFile()` function is in a child controller. The problem is likely a scoping issue and the question does not provide enough information for an adequate answer. See [AngularJS Developer Guide - Scope Hierarchies](https://docs.angularjs.org/guide/scope#scope-hierarchies). – georgeawg Jun 13 '18 at 19:54
  • @georgeawg, yes , problem is because directive scope is not controller scope. any suggestion for it would be helpful – mahipal singh Jun 13 '18 at 20:03
  • Problems with data hiding can be avoided by binding to a property of an object. Similar to the "best practice" of always have a '.' in your ng-models. Watch this [YouTube video](http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m) Misko demonstrates the primitive binding issue with `ng-switch`. – georgeawg Jun 13 '18 at 20:08
  • @georgeawg great example! my function is in child controller with `ng-switch` , that is why only scope is not updated. – mahipal singh Jun 13 '18 at 20:22

0 Answers0