[英]AngularJs ng-options (ke,value) ng-model="selected" doesnt work
This is my Html:这是我的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).我的问题是我无法使选择的
ng-model
工作,对象的结构使它变得困难..(无法更改对象)。
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.最后,我的目的是使
<select>
带有第一个选择的选项"ALB":{"name":"Albania"}
并使其动态化,以便当我按其他选项进行$scope.selected
更改时。
您可以尝试以下行:
$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..."现在我有
<option>
value 和 key,感谢每一位试图帮助我的问题的人,我的问题是我添加了“item as value.name...”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.