JSON条目看起来像这样
"campaign_id": "2","customer_id": "1","title": "Purple monkey dishwasher","description": "perfectly cromulent","start_time": "19/09/2015 09:42:06","end_time": "19/10/2015 09:42:06"
而且我明智地宣布我的堕落
<select name="SelectCampaignForConnections" ng-model="connectionsCampaignDropDown" ng-options="campaign.title for campaign in campaigns" ng-change="ShowConnectionsForCampaign(connectionsCampaignDropDown)">
我初始化选择的模型…
$http.get(url) .success(function(data,status,headers,config) { if ($scope.connections.length > 0) $scope.connectionsCampaignDropDown = $scope.connections[0];
当下拉列表显示时,它包含每个JSON条目的title元素,但是它有一个初始空白条目.
我做错了什么?
[更新] @sheilak给了一个很好的anser:
In order for the dropdown to defaulted to a non-blank value,the value
of the variable passed to ng-model must equal one of the options
passed to ng-options.In your case where ng-options is populated by values of
campaign.title,it looks like the value passed to ng-model i.e.
connectionsCampaignDropDown should be populated with
$scope.connections[0].title rather than the whole object
$scope.connections[0].$scope.connectionsCampaignDropDown = $scope.connections[0].title;
但是,我宁愿传递一个完整的对象,而不仅仅是它的一个字段.
可以这样做吗?
(如果没有,那么我将只需要将标题传递给ng-change函数ShowConnectionsForCampaign(),然后它必须遍历数据以找到匹配,这看起来效率低下)
解决方法
<select name="SelectCampaignForConnections" ng-init="justGiveItAName=getInitialSelection()" ng-model="justGiveItAName" ng-options="campaign.title for campaign in campaigns" ng-change="ShowConnectionsForCampaign(justGiveItAName)">
其中getInitialSelection()是你的作用域上的一个函数,如果你需要它可以采用一个参数,但我可能会在上面概述的情况下使用这样的东西:
function getInitialSelection() {return connections[0]};
或者直接在ng-init中设置它:
ng-init="$scope.connections[0]"
(你可能不得不摆弄上面的代码 – 我没有测试过它).
顺便说一句 – ‘justGiveItAName’是其他地方可用的对象.
我现在测试了它;看到这些小提琴的工作示例:
直接在ng-init中设置:http://jsfiddle.net/lukkea/nuo2c3Lk/
使用$scope:http://jsfiddle.net/lukkea/o6strxjf/上的函数
传递对象而不是属性(如请求的OP):http://jsfiddle.net/lukkea/fsx8s67j/2/