Click trigger event of another element in angular?

I have an input field and its binding to datepicker. In my opinion, in addition to this input field, there is a small calendar icon. I want to trigger an input window click event when a user clicks on this calendar icon. I did this with a directive that I applied to the calendar icon. But it's almost like jQuery. So is there any other way to achieve this? If my approach is wrong, please direct me in the right direction. I am new to angular and I read some articles in which I read that I avoid using jQuery. Thanks

My Directive

 myApp.directive('openCal',function($compile,$filter) { return { link:function(scope,element,attrs) { element.bind("click",function() { element.siblings("input").trigger("click"); }); } }; }); 

Works great. But I'm not sure if this is the right approach or not?

+4
source share
2 answers

No, if I understand what you are trying to do, you complicate things a bit.

In your case, it looks like you have something like:

 <img open-cal/> <input ng-click="doSomething()"> 

If you click on the img button, click on the tab using the openCal directive. Instead, you need to do something like this:

 <div ng-click="doSomething()"> <img> <input> </div> 

If doSomething () needs to get data from input, use ng-model to bind data from your input to your area.

ALTHOUGH! If you ever need to make a directive, this is the right way to do it. Using element.bind is not a problem as it is included in Angular. What you want to avoid is to use things like $ ('. Calendar'). Click etc.

0
source

Another way to approach this is to add the <label> element for the input field containing the calendar. Then clicking on the calendar will focus the input field. Then all you have to do is listen for the focus event in your input field to do the extra work. This has the added bonus of working if someone goes to your input field via the keyboard by pressing the tab key.

0
source

Source: https://habr.com/ru/post/1497991/


All Articles