Imo
Imo

Reputation: 1475

how to trigger a diffrent function each time an item is selected from a dropdown menu

I have a dropdown menu with values one, two and three and three different functions how can I trigger each function when I select one value for example if I select one function one triggers if I select value two function two triggers etc.

<select class='mapDropDown' ng-options='x for x in name' ng-model='selectedFunction'>
<option value=''> Please Select </option>
</select>

app.js

 function MyCtrl($scope) {
        $scope.name = ['one', 'two', 'three']

        function one(){
        alert('you triggered first function')
        }

        function two(){
        alert('you triggered second function')
        }

        function three(){
        alert('you triggered second function')
        }
    }

jsfiddle

Upvotes: 0

Views: 55

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You could pass current selected value myFunction method & then that method will decide how to call other method like below on change of select box. For taking effect of the same you need to place all the function in scope.

Markup

<select class='mapDropDown' ng-options='x for x in name' ng-model='selectedFunction'
  ng-change="myFunction(selectedFunction)">
   <option value=''> Please Select </option>
</select>

COde

$scope.myFunction = function(functionName){
   $scope[functionName]();
}

If you don't wanted to put methods in $scope you could put them inside the service and call them as we were doing for first approach. If you want to stay function there in controller rather than adding in scope, you could use below function

$scope.myFunction = function(functionName) {
   eval(functionName+'()')
}

Demo Fiddle

Upvotes: 1

Rui Costa
Rui Costa

Reputation: 800

$('.mapDropDown').change(function(){
 functionName = this.value; 

 function(functionName){
   $scope[functionName]();
 }
})

Upvotes: 1

Related Questions