Gourav khanna
Gourav khanna

Reputation: 79

how to get selected value from Drop-down, if drop-down is binded with keys of json

I am very new to Angularjs, I have binded column names(keys from key value pair) to the select list and want to get the key name on change of selection of select. Select list is showing:

name, snippet and age

And on selection change i want the selected text of select. Please help Here is my code:

<!DOCTYPE html>

<div ng-controller="HelloController">

    <h2>Hello {{helloTo.title}} !</h2>
    <select ng-options="key for (key,val) in phones[0]" ng-change="ChangeValue(key)" ng-model="phones"></select>
</div>


<script>
    angular.module("myapp", [])
        .controller("HelloController", function ($scope) {
            $scope.helloTo = {};
            $scope.helloTo.title = "World, AngularJS";
            $scope.phones = [
                {
                    'name': 'Nexus S',
                    'snippet': 'Fast just got faster with Nexus S.',
                    'age': 1
                },
                {
                    'name': 'Motorola XOOM™ with Wi-Fi',
                    'snippet': 'The Next, Next Generation tablet.',
                    'age': 2
                },
                {
                    'name': 'MOTOROLA XOOM™',
                    'snippet': 'The Next, Next Generation tablet.',
                    'age': 3
                }
            ];
            $scope.ChangeValue = function (selectedval) {

                alert(selectedval.name);
            };
        });
</script>

Upvotes: 0

Views: 361

Answers (1)

s.alem
s.alem

Reputation: 13079

<select ng-options="key as key for (key,value) in phones[0]" ng-change="ChangeValue()" ng-model="selectedVal"></select>

And the controller:

angular.module("myapp", [])
        .controller("HelloController", function ($scope) {
$scope.helloTo = {};
  $scope.helloTo.title = "World, AngularJS";
  $scope.selectedVal = '';
  $scope.phones = [{
    'name': 'Nexus S',
    'snippet': 'Fast just got faster with Nexus S.',
    'age': 1
  }, {
    'name': 'Motorola XOOM™ with Wi-Fi',
    'snippet': 'The Next, Next Generation tablet.',
    'age': 2
  }, {
    'name': 'MOTOROLA XOOM™',
    'snippet': 'The Next, Next Generation tablet.',
    'age': 3
  }];
  $scope.ChangeValue = function() {

    console.log($scope.selectedVal);
  };
});

It's right in the documentation actually...

Here's a plunker.

Upvotes: 1

Related Questions