Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call AngularJS function from select > option

Tags:

html

angularjs

I need to call an AngularJS function from selection:

<select ng-model="selection" >
<option onselect="angular.element(this).scope().functionCall('one')">one</option>
<option onselect="angular.element(this).scope().functionCall('two')">two</option>
<option onselect="angular.element(this).scope().functionCall('three')">three</option>
<option onselect="angular.element(this).scope().functionCall('four')">four</option>
</select>

However, the function never gets called.

In the controller,

$scope.functionCall = function(value){
// do stuff with value
}

How can I call the function.

like image 527
user3779089 Avatar asked Sep 11 '14 22:09

user3779089


People also ask

How to call function in select option tag in AngularJS?

selectedItemChanged = function(){ console. log($scope. selectedItem); } }); You will notice that when the select option is changed, a function gets called which will give the you the value of the current selected value.

How to use select in AngularJS?

HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.

How to use dropdown in AngularJS?

You should use the ng-option directive to create a dropdown list, based on an object or an array in AngularJS. See this example: <! DOCTYPE html>


1 Answers

It's recommended that you use ng-change for that matter, the result may be the same as Cyril's, but the code is more readable and testable, also it is considered a better practice:

Here is a plunker demonstrating it in action: http://plnkr.co/edit/7GgwN9gr9qPDgAUs7XVx?p=preview

app.controller('MainCtrl', function($scope) {
  $scope.listOfOptions = ['One', 'Two', 'Three'];

  $scope.selectedItemChanged = function(){
    $scope.calculatedValue = 'You selected number ' + $scope.selectedItem;
  }
});

And the HTML:

<select ng-options="option for option in listOfOptions" 
        ng-model="selectedItem"
        ng-change="selectedItemChanged()">
</select>

Hope that helps. Thanks.

like image 67
Fedaykin Avatar answered Oct 08 '22 16:10

Fedaykin