3

I've been trying to trigger a click event in my input element using a angular ng-click in other element, like this:

html

<div class="myClass" ng-click="vm.selectImage()" nv-file-drop uploader="vm.uploadImage">
    Drop your image here
</div>
<div ng-hide="!hideInput">
    <input type="file" id="imgSelect" nv-file-selec uploader="vm.uploadImage" />
</div>

controller

vm.selectImage= selectImage;
function selectImage() {
    angular.element('#imgSelect').trigger('click');
};

I know there is other similar questions to this, but I've tried to use what they said (which a bunch of them shows the same code I'm using), for example:

But even with that, or even using a directive like this:

.directive('selectImg', selectImg);
function selectImg() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            element.bind('click', function(e) {
                //option 1
                angular.element(e.target).siblings('.imgSelect').trigger('click');

                //option 2
                angular.element( document.querySelector( '#imgSelect' ) ).trigger('click');

                //option 3
                var myEl = angular.element( document.querySelector( '#imgSelect' ) );
                myEl.trigger('click');

                //option 4
                angular.element('#imgSelect').trigger('click'); //angular way
            });
        }
    };
}; 

I keep getting this error:

Error: [jqLite:nosel] http://errors.angularjs.org/1.5.0-beta.1/jqLite/nosel

Here is a plunker to demonstrate the error: http://plnkr.co/edit/rWcCbixwFArYhCxUVTsv?p=preview

What is the problem?

6
  • Please create a plunkr that demonstrates the problem Commented Nov 28, 2015 at 12:46
  • @GaneshKumar I've updated my question with a plunker. Commented Nov 28, 2015 at 13:04
  • The problem is that you are not doing it Angular way, so not surprisingly it doesn't work. All your versions are not reliable, because they try to deal with DOM that is not in directive context, so the template is likely not be in DOM when you try to use it. Commented Nov 28, 2015 at 13:06
  • angular.element() does not have trigger() method. docs.angularjs.org/api/ng/function/angular.element Commented Nov 28, 2015 at 13:09
  • remove the selectors or add jquery,jqury lite doesnt support selectors Commented Nov 28, 2015 at 13:10

1 Answer 1

5

ok updated my answer this works.It appears that you have to break out of the current $apply() cycle. One way to do this is using $timeout()

setTimeout(function() {
    document.getElementById('imgSelect').click()        
 }, 0);

check answer Trigger input file click event in AngularJS

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

1 Comment

There is no more errors in the console. But shouldn't it open the input to add a file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.