简体   繁体   中英

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.

您可以尝试以下行:

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

 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>

    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..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM