user3194721
user3194721

Reputation: 815

Angularjs ng-options with an array of key-pair

I'm having below array. I'm trying different ng-options but no use. How to render in Drop down using Angularjs ng-options?

getLanguages: [0: Object: Key:"en" Value:"English", 1: Object: Key:"fr" Value:"France"]

<select ng-options="language.Object.Value for language in getLanguages track by language.Object.Value"/>

<select data-ng-model="vm.model">
    <option data-ng-repeat="language in getLanguages" value="{{language.Object.Key}}">{{language.Object.Value}}</option>
</select>

I got Answer:

<select class="form-control" data-ng-model="vm.model" >
    <option data-ng-repeat="language in vm.getLanguages()" value="{{language.Key}}">{{language.Value}}</option>
</select>

Upvotes: 0

Views: 1599

Answers (3)

user5471213
user5471213

Reputation:

angular.module('app', []).controller("controllername", ["$scope", function($scope) {
    $scope.getLanguages = [
        {"en":"English"},
        {"fr":"French"}
    ];

    $scope.getKey = function(getLanguages) {
        return Object.keys(getLanguages)[0];
    }
}]);

Upvotes: 0

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15209

Really the answer is a combination of both David and Stark's answers above.

First you need to make sure your controller is correctly returning the languages, as Stark indicated in his answer.

For example, it should include something like:

$scope.languages = [
  { key : "en",
    value : "English" },
  { key : "fr",
    value : "French" }];

Then you can populate your <select> options using those languages. As David pointed out, the correct syntax would be similar to the following:

<select ng-model="model.language"
        ng-options="language.key as language.value for language in languages">

What this syntax is saying is "show the 'value' in the drop down and map it to the 'key' for each 'language' in the collection returned by the 'languages' variable in the scope." So the drop down will show "English", "French", etc., and when you select one, it will set the model value to "en", "fr", etc.

Here is a working Plunkr showing the above in action.

Upvotes: 0

David Meza
David Meza

Reputation: 3180

Try ng-options = "language.Object.Key as language.Object.Value for language in getLanguages()"

Upvotes: 1

Related Questions