2

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);

2 Answers 2

1

For trigger the file selector open programmatically, the answer is yes.

But you need to make sure this event was fired by THE USER.

For example, you have a button there, you attach the click event on it. After the user click this button, inside the event handler, you can trigger by javascript code e.g,document.getElementById('fileInput').click(). This should work.

However, if you want to simply run several lines of javascript code to open a file selector without user's click, that's not possible, because that violate the security policy.

So I added some code to your sample,

html,

<button ng-click='open()'>Open selector</button>

javascript,

$scope.open = function() {
     document.getElementById('fileInput').click(); //this work
};

Hope this would solve your problem. : )

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

Comments

1

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.

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.