Heim > Fragen und Antworten > Hauptteil
在做省市联动。option中value是省市编码 text是名称,
如何才能既确定selected选项,又获取text名称?
曾经蜡笔没有小新2017-05-15 17:02:31
使用ng-options就行啊
代码加载有些慢。。稍等一下可以看到效果:
http://codepen.io/flybywind/pen/GZyydY
怪我咯2017-05-15 17:02:31
<p ng-controller="MyCtrl">
<select ng-model="province">
<option value="">--province--</option>
<option ng-repeat="p in provinces" value="{{p.value}}">{{p.text}}</option>
</select>
<select ng-model="city">
<option value="">--city--</option>
<option ng-repeat="c in citys" value="{{c.value}}">{{c.text}}</option>
</select>
</p>
angular.module('myApp', [])
.controller('MyCtrl', function ($scope) {
$scope.province = '';
$scope.city = '';
$scope.citys = null;
$scope.provinces = [
{
value: 1,
text: 'jiangsu',
citys: [
{
value: 1,
text: 'nanjing'
}
]
},
{
value: 2,
text: 'anhui',
citys: [
{
value: 1,
text: 'hefei'
}
]
}
];
$scope.$watch('province', function (value) {
if (!value) {
$scope.citys = null;
} else {
$scope.citys = $scope.provinces.filter(function (p) {
return value == p.value;
})[0].citys;
}
$scope.city = '';
});
});
曾经蜡笔没有小新2017-05-15 17:02:31
其实是我的问题,问题的解决根本是ng-model直接绑对象,然后option的value也绑相同的对象,这样就解决了'选中问题',在后台取id或文本值,直接是对象的id或text。thanks!
ringa_lee2017-05-15 17:02:31
在angularJS的官方文档上就有,需要自备梯子
下面是我用的1.4.7的版本的文档中的示例
<p ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
</p>
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
repeatSelect: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
};
}]);
结果就是option中显示的是name部分,model获得的是id,这里model用的是data.repeatSelect是因为循环是在option上,而导致作用域的不同