Search code examples
javascriptangularjsng-img-crop

Trigger <input type="file"> file select with angular programatically


Im using ngImgCrop as can be seen in this JSFiddle.
What I try to achieve is that the image selection box will open automatically when i show(using ng-if) the:

<div ng-if="showImageSelector">
 <div>Select an image file: <input type="file" id="fileInput" /></div>
 <div class="cropArea">
  <img-crop image="myImage" result-image="myCroppedImage"></img-crop>
 </div>
</div>

that is: i want to programatically open the image selection window, without even showing the user the:

<input type="file" id="fileInput" />

Iv'e tried put in the controller several variations of click event of the input, but none of them worked, so far iv'e tried: 1.

$timeout(function() {
    angular.element('#fileInput').triggerHandler('click');
  }, 0);

2.

angular.element(document).ready(function () {
    angular.element('#fileInput').triggerHandler('click');
  });

3.

setTimeout(function(){
    angular.element('#fileInput').triggerHandler('click');
  }, 1000);

4.

setTimeout(function(){
    document.getElementById('fileInput').click();
  }, 1000);

Solution

  • Ended up wrapping the ngImgCrop with my directive, in it iv'e placed that:

    $timeout(function () {
          angular.element(document.querySelector('#fileInput')).click();
          $log.debug("poped it");
        }, 250);
    

    in the link function. Aside the real element i show for the img selector, iv'e placed this at my index.html:

    <div ng-show="false">
      <my-image-select cropped-image="groupDetails.newPic" return-func="groupDetails.imageSelectFinish"></my-image-select>
    </div>
    

    and it works. without the extra invisible my-image-select in index.html, the file chooser only auto open from the second attempt.