Alex
Alex

Reputation: 425

AngularJs ng-options (ke,value) ng-model="selected" doesnt work

This is my Html:

<select ng-options="value.name for (key, value) in countries track by key" ng-model="selected" >
</select>

This is the object im trying to work on:

$scope.countries = {
    "AFG":{"name":"Afghanistan"},
    "ALB":{"name":"Albania"}
};
$scope.countriesKeys = Object.keys($scope.countries);
$scope.selected = ????;

My problem is that I can't manage to make the ng-model selected to work, the object's structure makes it difficult.. (can't change the object).

In the end my purpose is to make the <select> with a first selected option "ALB":{"name":"Albania"} and make it dynamic so when I press other options to make $scope.selected change.

Upvotes: 1

Views: 71

Answers (3)

amit banerjee
amit banerjee

Reputation: 61

You may try the following line:

$scope.selected={"name":"Albania"}

Upvotes: 1

Alex
Alex

Reputation: 425

    var getKeyByValue = function( value,array1 ) {
for( var prop in array1 ) {
    if( array1.hasOwnProperty( prop ) ) {
         if( array1[ prop ] === value )
             return prop;
    }
}

I have added this function to my controller

getKeyByValue($scope.selected,$scope.countries)

now I have both value and key from the <option> Thank for every one who tried to help mostly my problem was that I added "item as value.name..."

Upvotes: 0

Pradeepb
Pradeepb

Reputation: 2562

var app = angular.module("myApp", []);

//controller
app.controller('MainCtrl', function($scope) {
    $scope.countries = {
        "AFG":{"name":"Afghanistan"},
        "ALB":{"name":"Albania"}};
        $scope.countriesKeys=Object.keys($scope.countries);
        $scope.selected="ALB";
  
        $scope.changeSelected = function(newSelected){
            $scope.selected=newSelected;
        }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">

  <div class="div1" ng-controller="MainCtrl">
    {{selected}}
    <select ng-options="key as value.name for (key, value) in countries" ng-change="changeSelected(selected)"  ng-model="selected"></select>
  </div>

</body>

Upvotes: 0

Related Questions