1

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);
    }
});
3
  • I think ng-options simply isn't set up to handle this. Ng-repeat will allow you to do this, but I'm not sure ng-change will. But you should be able to handle this with a simple watch in your controller. $scope.$watch('ddlFruits', function(new, old){ if (new !== old) { GetValue(new) }}); Commented Jun 29, 2016 at 5:23
  • @JohnHalbert if i use ng-repeat, i think i wont be able to use track by option.. Commented Jun 29, 2016 at 5:31
  • I think my response was somewhat poorly worded. I don't think you should use ng-repeat, I simply was contrasting ng-options functionality with ng-repeat. Track by will work with ng-repeat. But I don't believe ng-options will allow you to pass the repeated object to ng-change the way ng-repeat will. This is what i was trying to say. Setting a watch is my suggestion. Commented Jun 29, 2016 at 5:35

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

if i remove " as " I can get the whole object as well. solves my purpose.
0

This will get you fruits

HTML

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

  $scope.GetValue = function (val) {
    alert(val.Fruits[val.ddlFruits].Name);
  }

and this will give you selected value

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.