2016-02-23 201 views
0

我正在创建角度选择标签。根据我已阅读的许多网站和一些帖子,它说当使用选择标签不在选项标签上使用“ng-repeat”,但在选择标签上使用“ng-options”时,这就是我如何设置它向上。我的问题是,我想默认选择一个特定的选项标签,我如何使用此方法设置选定的属性?角选择标签

<select class="form-control" ng-model="selected_group" ng-change="new_group($event)" ng-options="group as (group.group_name | decodeuri) for group in groups"></select> 

回答

0

您可以添加一个<option>标签:

<select class="form-control" ng-model="selected_group" ng-change="new_group(selected_group)" ng-options="group as (group.group_name | decodeuri) for group in groups"> 
    <option value="">Please Select an Option</option> 
</select> 
1

选择一个默认的很简单:设置selected_group等于你的控制器某一特定群体。

其基本思想是你有一个集合,选定的选项将被存储在你的ng-model。要从一开始就指定一个选择,您需要在ng-model中添加一些内容。这将不得不在你的控制器中。

+0

如何?我试过ng-init =“selected_group = 1”,这是行不通的。 –

+0

不通过ng-init。在您的控制器中,执行像'$ scope.selected_group = $ scope.groups [0];' – bbrown

+0

这样的操作,不应该像@ LJ.Wizard所示的那样使用ng-init:请参阅文档中的红色警告 - https: //docs.angularjs.org/api/ng/directive/ngInit – bbrown

0

在这里,我已经创建小型工作demo

<div ng-app="myApp" ng-controller="myCtrl"> 
<select class="form-control" ng-model="option.group" ng-options="group as (group.name | myfilter) for group in groups"> 
</select> 
</div> 


var app = angular.module('myApp', []); 
app.filter('myfilter', function() { 
    return function(v) { 
    return v == 'test3' ? 'filtered test3' : v; 
    }; 
}); 
app.controller('myCtrl', function($scope) {  

$scope.groups = [{id:1,name:'test1', phone:'1234567890'}, 
         {id:2,name:'test2', phone:'1234567890'}, 
         {id:3,name:'test3', phone:'1234567890'} 
        ]; 

$scope.option={      
    group: $scope.groups[1] 
    }      

});