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.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With