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?

Community
  • 1
  • 1
celsomtrindade
  • 4,501
  • 18
  • 61
  • 116
  • Please create a plunkr that demonstrates the problem – Ganesh Kumar Nov 28 '15 at 12:46
  • @GaneshKumar I've updated my question with a plunker. – celsomtrindade Nov 28 '15 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. – dfsq Nov 28 '15 at 13:06
  • angular.element() does not have trigger() method. https://docs.angularjs.org/api/ng/function/angular.element – Ganesh Kumar Nov 28 '15 at 13:09
  • remove the selectors or add jquery,jqury lite doesnt support selectors – Mat. Nov 28 '15 at 13:10
  • Then why the other answers tell to do it, and are acceptable? Or, how should I do it with only AngularJs? I have no plans to insert jQuery in my project. – celsomtrindade Nov 28 '15 at 13:10

1 Answers1

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

Community
  • 1
  • 1
Mat.
  • 541
  • 2
  • 11