我看到无限的帖子试图在下拉菜单中默认选择一个选项。但我无法实现它。我有一些国家。
$scope.regions =
[
{
name: "COLOMBIA",
code: 5
},
{
name: "ARGENTINA",
code: 6
},
{
name: "BRAZIL",
code: 7
}
];
我有这个变量:
$scope.selectThisId={
"id":6,
"animal":'dog',
"variable":'xxx32'
};
我需要下拉值等于
的id属性$scope.region=$scope.selectThisId.id;
变量。
答案 0 :(得分:4)
工作演示:http://plnkr.co/edit/zhye91pDUEMgaZnXZGWE?p=preview
您基本上可以通过
创建默认区域$scope.select = $scope.selectThisId.id;
$scope.regionSelected = {};
然后使用select
创建ng-options
标记,将其绑定到模型,并在模型上调用ng-init
。
<select ng-options="item as item.name for item in regions track by item.code"
ng-model="regionSelected" ng-init="regionSelected.code = select">
</select>
答案 1 :(得分:0)
您可以向控制器添加过滤器以获取默认区域(不要忘记在$filter
之后添加$scope
):
$scope.defaultValue = $filter('filter')($scope.regions, {code: $scope.selectThisId.id}, true)[0];
然后将其添加到您视图中的选择
ng-init="select = defaultValue"
答案 2 :(得分:0)
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.regions =
[
{
name: "COLOMBIA",
code: 5
},
{
name: "ARGENTINA",
code: 6
},
{
name: "BRAZIL",
code: 7
}
];
$scope.selectThisId={
"id":6,
"animal":'dog',
"variable":'xxx32'
};
$scope.region=$scope.selectThisId.id;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
<select
ng-options="item.code as item.name for item in regions"
ng-model="region"></select>
</fieldset>
</div>