Abdul Rehman Sayed Abdul Rehman Sayed - 5 months ago 13
Javascript Question

Angular js pass selected object to a change event for dropdown/select:

Plunkr :
http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview

I am trying to pass the selected item of the dropdown to a function in my controller.

However, I am getting it as undefined.

HTML :

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>

<body>
<h1>Hello Plunker!</h1>

<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlFruits"
ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
ng-change="GetValue(fruit)">
</select>
</div>

</body>

</html>


Script :

var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];

$scope.GetValue = function (fruit) {
alert(fruit);
}
});

Answer

Hi froM HTML change this

ng-change="GetValue(ddlFruits)"

from console you will get id of the selected one

<select ng-model="ddlFruits" 
        ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
            ng-change="GetValue(ddlFruits)">
        </select>
Comments