0

I have upload file feature and writing the filename inside input box, but when I upload file next time, the ng-model inside input won't update the filename as newer.How to update ng-model everytime I select new file. Here is the code.

JS:
$scope.setFile = function(element) {
    $scope.$apply(function($scope) {
        $scope.myFile = element.files[0];
        $scope.FileName=$scope.myFile.name;
        $scope.FileName = $scope.FileName.replace(/\..+$/, '');
        $scope.fileExtension =  element.files[0].name.split('.').pop();
        console.log($scope.FileName);
        console.log($scope.fileExtension);

    });
};

HTML code:
<input type="file" name="upload" ng-model="diagram"  onchange="angular.element(this).scope().setFile(this)" base-sixty-four-input>
<p>Tags:</p>
<p><input type="text" class="form-control  input-sm" ng-model="FileName" ></p>

Any help is appreciated. Thanks

Helping hand
  • 2,800
  • 2
  • 19
  • 31
  • Try $scope.$apply(function() { instead of $scope.$apply(function($scope) { – Ruhul Aug 22 '16 at 12:34
  • Please have a look at working demo http://www.java2s.com/Tutorials/AngularJS/AngularJS_Example/Controller/Call_function_in_controller_with_onchange_event.htm . – Ruhul Aug 22 '16 at 12:40
  • Possible duplicate of [File Upload using AngularJS](http://stackoverflow.com/questions/18571001/file-upload-using-angularjs) – RIYAJ KHAN Aug 22 '16 at 12:58

2 Answers2

0

Can you please try this?? No need to pass $scope to apply.

$scope.setFile = function(element) {
    $scope.$apply(function() {
        $scope.myFile = element.files[0];
        $scope.FileName=$scope.myFile.name;
        $scope.FileName = $scope.FileName.replace(/\..+$/, '');
        $scope.fileExtension =  element.files[0].name.split('.').pop();
        console.log($scope.FileName);
        console.log($scope.fileExtension);

    });
};
Ruhul
  • 990
  • 7
  • 15
0

Don't use $scope.apply, but use the safer $timeout service:

$scope.setFile = function(element) {
   $timeout(function(){
       $scope.myFile = element.files[0];
       $scope.FileName=$scope.myFile.name;
       $scope.FileName = $scope.FileName.replace(/\..+$/, '');
       $scope.fileExtension =  element.files[0].name.split('.').pop();
       console.log($scope.FileName);
       console.log($scope.fileExtension);
   }, 0);
};

This way, your bindings will be always up-to date with your events (and thus, your $scope.variable will be assigned).

If this does not fix your problem, you may have a problem with scopes and/or your variable is misassigned elsewhere.

illeb
  • 2,942
  • 1
  • 21
  • 35
  • I am getting no problem in printing filename in console n number of times, but ng-model will take filename as input only once. $timeout isn't working as well. – Helping hand Aug 22 '16 at 17:32