1

I have a strange problem with my AngularJS project. I have 2 buttons that trigger inputs below.

<button type="button" class="btn btn-primary" data-ng-click="triggerInput('B1')">B1</button>
<input id="b1Input" type="file" accept="image/*" class="hide" onchange="angular.element(this).scope().changeImage(this)" />

<button type="button" class="btn btn-primary" data-ng-click="triggerInput('B2')">B2</button>
<input id="b2Input" type="file" accept="image/*" class="hide" onchange="angular.element(this).scope().changeImage(this)" />

I tried to debug the JS code, but it seems to be okay. Unfortunatelly, Sometimes I have to click chosen button couple times (2-4) to make the input open. Maybe the jQuery selector is bad?

Here's the code:

$scope.triggerInput = function (type) {
    $timeout(function () {
        var selector = "";
        switch (type) {
            case "B1":
                selector = "b1Input";
                break;
            case "B2":
                selector = "b2Input";
                break;
        }

        $("input[id='" + selector + "']").trigger("click");
    });
};
Nickon
  • 9,652
  • 12
  • 64
  • 119

1 Answers1

1

You should not use this line(which is below) into controller. I think you can write a directive to populate this.

$("input[id='" + selector + "']").trigger("click");

Correct your code

<button type="button" class="btn btn-primary" data-ng-click="triggerInput('B2',$event)">B2</button>


$scope.triggerInput = function (type,e) {
    $timeout(function () {
        var selector = "";
        switch (type) {
            case "B1":
                selector = "b1Input";
                break;
            case "B2":
                selector = "b2Input";
                break;
        }

       angular.element(e.target).siblings('#'+selector).trigger('click');
       //or simply write this
       //$("#"+selector).trigger("click");
    });
};
Community
  • 1
  • 1
Shohel
  • 3,886
  • 4
  • 38
  • 75
  • Thank you, sir. Could you explain why I shouldn't use this line `$("input[id='" + selector + "']").trigger("click");`? How this differs from `$("#"+selector).trigger("click");`? – Nickon Nov 02 '15 at 10:30
  • Yes, it is. But I can't understand why – Nickon Nov 02 '15 at 12:46