2016-05-27 50 views
0

我想创建一个带有“selected”值的select标签。我正在用ng-repeat这样做,因为我无法将自定义指令添加到ng-options。这是代码。Angular:ng-options添加自定义指令

<select class="ng-valid ng-dirty" ng-model="selectedCity"> 
     <option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option> 
    </select> 

这增加了一个额外的选项value =?string:1?我搜查了很多。由于ng-options解决了这个问题,但是我必须为每个选项添加指令渲染后城市。我该如何解决这个问题?

+1

*“但我必须为每个选项添加指令后渲染城市”*。为什么渲染后的城市做了什么? – dfsq

+0

它是一个android cordova应用程序。数据在html中呈现后隐藏启动画面。 –

+0

你仍然可以隐藏它,你不需要这个指令。 – dfsq

回答

0

使用ng-init解决value =?string:1?

<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-init='selectedCity=allCities[0].id'> 
    <option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option> 
</select> 

另一种选择,你可以使用NG选择fiddle

<option ng-repeat="(key,city) in allCities" ng-selected='key==0' value="{{city.id}}" after-render-cities>{{city.name}}</option> 
</select> 
+0

ng-init工作。但我不得不删除ng模型。用ng模式它不起作用。 –

+0

你为什么要删除ng模型? – aseferov

+0

不知道。但它不适用于ng-model。现在我试图在'change'事件上将值与ng-model绑定 –

0

使用此

<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-options="city.id as city.name for city in allCities"> 
</select> 

的第一个值的选择,在你的控制器写下面的代码

$scope.selectedCity = $scope.allCities[0].id; 
0

试试S码

Java脚本

var app = angular.module('myApp', []); 
app.controller('SampleController', function ($scope) { 
    $scope.Cities = [ 
     { Id: 1, Name: "New York" }, 
     { Id: 2, Name: "Colombo" }, 
     { Id: 3, Name: "Real Madrid" }, 
     { Id: 4, Name: "Bostan" }, 
     { Id: 5, Name: "Birmingham" } 
     ]; 
    $scope.City= 3; 
}); 

HTML

<select ng-options="C.Id as C.Name for C in Cities" ng-model="City"></select> 

Read This Blog, it has everything explained.

0

您可以创建自定义directive,使用selectng-options

片段

JS:

template: "<select ng-options='item.id as item.name for item in list' ng-model='data'></select>", 

HTML:

<div select-option list="list" ng-model='data'></div> 

参考演示here