1

I'm trying to create an upload button.

HTML

<div class="parent">
  <input id="uploadFile" type="file" ng-model="uploadFile">
  <div class="child">
  <span>select a file</span>
  </div>
</div>

JS

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

function MyCtrl($scope) {
    $scope.$watch('uploadFile', function(val) {
        if (val) {
            console.log(val);
        }
    });
}

So I have hidden default input type file by adding some opacity in CSS and what I need is to take the value from the input type file and replace the span value with the value from input, also need an "x" close button that will delete the span and input value.

FIDDLE:

mcmwhfy
  • 1,654
  • 5
  • 36
  • 58
  • Possible duplicate of [get source and name of selected file with angularjs](https://stackoverflow.com/questions/27227788/get-source-and-name-of-selected-file-with-angularjs) – Castro Roy Sep 20 '17 at 15:08

2 Answers2

-1

No need to write any JS code, its Angular, just change your HTML a little bit:

<div class="parent">
  <input id="uploadFile" type="file" ng-model="uploadFile">
  <div class="child">
  <span ng-bind="uploadFile">select a file</span>
  </div>
</div>

<span ng-bind="uploadFile">select a file</span>

  • Add `ng-controller="MyCtrl"` to your div and everything will work : your solution and the better written one of Syed – Genu Sep 20 '17 at 13:04
  • @Genu yes but is still not working, check that in fiddle – mcmwhfy Sep 20 '17 at 13:09
  • @SyedAmirHussain it is but is not working, I think the solution with ng-binding is not quite accurate – mcmwhfy Sep 20 '17 at 13:14
  • Your Fiddle works by adding ng-controller. It prints the file name in the console. I understand that you want more feature, but fix your initial post then, and answers will focus on a solution to provide this feature. – Genu Sep 20 '17 at 13:16
  • @Genu that is not true because the generated window is a system window and jsfiddle will help you with that but if you put that in a working project will not work – RulerNature Sep 20 '17 at 13:34
-1

I think you want to show the image that you just uploaded, if yes please use the below code:

HTML:

<div class="parent">
  <input id="uploadFile" type="file">
  <div class="child">
  <span class="choose_file">select a file</span>
  </div>
</div>

JS:

    angular.element('.choose_file').click(function(){
        angular.element('#uploadFile').trigger('click');
    });
    angular.element('#uploadFile').change(function(){
        readFile(this);
    });
    var readFile = function(obj) {
        if(obj.files && obj.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
        angular.element('.'+angular.element(obj).attr('name')).html('<img src="'+e.target.result+'" height="50" />');
            }
            reader.readAsDataURL(obj.files[0]);
        }
    }