underscore
underscore

Reputation: 6887

get selected value in angular ng-option

I have an object like bellow:

var data = {
    BCS: ['a', 'b', 'c', 'd'],
    HND: ['e', 'f', 'g', 'h'],
    LMU: ['i', 'j', 'l', 'm']
};

And Bellow is my controller

function getDivision($scope) {
    $scope.divisions = data;
}

And this is model

<div ng-app>
    <div ng-controller='getDivision'>
        <select ng-model="key" ng-options="key for (key , val) in divisions" ng-change="update()"></select>
        <select ng-model="divisionValues" ng-options="value for value in key"></select>
    </div>
</div>

This is JsFiddle

How can i get first selected value and parse it to the controller ?

Upvotes: 1

Views: 15302

Answers (2)

Marc Kline
Marc Kline

Reputation: 9409

Your expressions should look like the following:

<select ng-model="key"ng-options="key as key for (key, val) in divisions"
ng-change="update()"></select>

<select ng-model="divisionValues"
ng-options="value for value in divisions[key]"></select>

This combination will allow your users to select from the keys of data, and once they do, the second select box will contain the four letters associated with them in the associated value array.

The expressions are tricky and hard to understand at first, but if you read the docs a few times and experiment, it will all make sense.

Working Fiddle

Upvotes: 1

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

You have to pass the key to the update method like ng-change="update(key)"

Working Demo

html

<div ng-app>
    <div ng-controller='getDivision'>
        <select ng-model="key" ng-options="key as key for (key, val) in divisions" ng-change="update(key)"></select>
        <select ng-model="divisionValues" ng-options="value for value in divisions[key]"></select>
    </div>
</div>

script

var data = {
    BCS: ['a', 'b', 'c', 'd'],
    HND: ['e', 'f', 'g', 'h'],
    LMU: ['i', 'j', 'l', 'm']
};

function getDivision($scope) {
    $scope.divisions = data;
    $scope.update = function (a) {
        console.log(a);
    }
}

Upvotes: 0

Related Questions