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");
    });
};
6
  • create a directive put your dom related logic there instead of doing what you are doing .. Commented Nov 2, 2015 at 8:45
  • Will it change anything? I think this solution should work as well Commented Nov 2, 2015 at 8:48
  • may be or may be not .. sometime angular.element(this).scope() need timeout to execute. Commented Nov 2, 2015 at 8:49
  • Hmm, that's why I added $timeout in triggerInput Commented Nov 2, 2015 at 8:52
  • that input won't effect onclick's angular.element(this).scope().changeImage(this) this portion also need timeout to call changeImage Commented Nov 2, 2015 at 8:52

1 Answer 1

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");
    });
};
Sign up to request clarification or add additional context in comments.

2 Comments

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");?
Yes, it is. But I can't understand why

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.