Angular ng-click for drodpdown option tag

11,846

Solution 1

ng-click will trigger when you click any element with that decorator, not the option. I think ng-change will probably be a better directive in your case.

Solution 2

Change <select ng-click="execute()"> to <select ng-change="execute()">

The ng-click gets executed whenever you click on the object (in this case, the dropdown). The ng-change gets executed when the form element is changed, which is whenever the user changes the dropdown item.

Solution 3

You need to use angular ng-change (ngChange).

Use

ng-change="execute()"

instead of

ng-click="execute()"

Doc Reference ng-change: https://docs.angularjs.org/api/ng/directive/ngChange

Doc Reference ng-click: https://docs.angularjs.org/api/ngTouch/directive/ngClick

Since you use ng-click, the click event fires at the time you click the select box. However if you use ng-change, the change event will fire when the select box's value change based on the option selection, thus execute() will fire.

Share:
11,846
Patrick
Author by

Patrick

Updated on June 27, 2022

Comments

  • Patrick
    Patrick almost 2 years

    Here is a jsfiddle. http://jsfiddle.net/cuycbxxp/

    I have a dropdown selection here for 2. names and numbers.

    Select name and then select numbers. once a dropdown is selected for numbers, execute function get executed and a output is displayed at the console.

    This might look like it is working fine. but open the console and click on the dropdown. execute function executes before we even select a dropdown option.

    How to ensure that execute function should execute only when the user clicks on one of the option tags ?

    Markup:

    <div ng-controller="MyCtrl">
        <div>
            <label>Names:</label>
            <select ng-model="params.name">
                <option value="pa">Taeo</option>
                <option value="ws">Wers</option>
                <option value="pn">Petin</option>
            </select>
            <br>
            <label>Numbers:</label>
            <select ng-click="execute()">
                <option value="22">22</option>
                <option value="33">33</option>
            </select>
        </div>
    </div>
    
    • thsorens
      thsorens almost 8 years
      ng-click will trigger when you click any element with that decorator, not the option. I think ng-change will probably be a better directive in your case ?
    • Patrick
      Patrick almost 8 years
      @thsorens- wld u like to put it as an answer ? i see others have answered it but u did it first. Thanks guys. my understanding is a tad better now with ng-click and ng-change.
    • thsorens
      thsorens almost 8 years
      I posted my answer now.