我正在尝试使用Angular JS填充多选项。这是我的清单
var depositoryList =[
{
"depos":"Any",
"deposName":"Any"
},
{
"depos":"DUB",
"deposName":"DUBAI"
},
{
"depos":"MUM",
"deposName":"MUMBAI"
},
{
"depos":"SNG",
"deposName":"SINGAPORE"
}],
// didnt Work
$scope.depositoryId = {value:{depos:'Any'}}
这是我在HTML中填充它的方式
<select multiple
ng-model="depositoryId.value"
data-ng-options="obj.depos + ' - ' + obj.deposName for obj in depositoryList track by obj.depos">
</select>
1)我试图将默认值设置为Any,我无法设置它们。
2)我试图获取所选值并发出警报($ scope.depositoryId.value.depos)。它给了我一个未定义的警报信息
我哪里出错了
答案 0 :(得分:1)
最终修改:
显示Any-任意没有任何中断并在ng-model中获取选定的值
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.depositoryId = ['Any'];
$scope.depositoryList =[
{
"depos":"Any",
"deposName":"Any"
},
{
"depos":"DUB",
"deposName":"DUBAI"
},
{
"depos":"MUM",
"deposName":"MUMBAI"
},
{
"depos":"SNG",
"deposName":"SINGAPORE"
}];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<head></head>
<body ng-controller="MainCtrl">
<select multiple="true" ng-model="depositoryId" ng-options="obj.depos as (obj.depos + ' - ' +obj.deposName) for obj in depositoryList">
</select>
<div>{{depositoryId}}</div>
</body>
</html>
&#13;
答案 1 :(得分:1)
对于没有硬编码初始值的更优雅的解决方案,因为你有数组中需要的字符串,你可以这样做:
<select multiple='true' ng-init="depositoryInitialValue = depositoryList[0].deposName"
ng-model="depositoryInitialValue"
ng-options="obj.depos as (obj.depos + ' - ' + obj.deposName) for obj in depositoryList">
</select>
请参阅plunkr here
希望它有所帮助。
var app = angular.module('ngApp', []);
app.controller('MainCtrl', ['$scope', function($scope) {
'use strict';
$scope.depositoryList = [{
"depos": "Any",
"deposName": "Any"
}, {
"depos": "DUB",
"deposName": "DUBAI"
}, {
"depos": "MUM",
"deposName": "MUMBAI"
}, {
"depos": "SNG",
"deposName": "SINGAPORE"
}]
}]);
&#13;
<!DOCTYPE html>
<html ng-app="ngApp">
<head lang="en">
<meta charset="utf-8">
<title>maxisam's ngApp</title>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
</head>
<body ng-controller="MainCtrl" class="container">
<br/>
<select multiple='true' ng-init="depositoryInitialValue = depositoryList[0].deposName" ng-model="depositoryInitialValue" ng-options="obj.depos as (obj.depos + ' - ' + obj.deposName) for obj in depositoryList">
</select>
<br /> {{depositoryInitialValue}}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
&#13;