加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:为什么我的下拉列表有一个初始空白条目?

发布时间:2020-12-17 07:09:14 所属栏目:安全 来源:网络整理
导读:我正在获取一些 JSON frm服务器并使用它来填充组合框. 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/2
我正在获取一些 JSON frm服务器并使用它来填充组合框.

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/

传递对象和对象:http://jsfiddle.net/lukkea/ww9yqsrm/3/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读