Javascript 所选ng选项项不存在';不要固守';组合框';
我是AngularJS的新手,正在努力做一些应该很容易的事情 我有一个难看的页面: 用户在此屏幕上添加新的啤酒,啤酒可能有多种风格-因此“添加”按钮会创建一个新的“风格”组合框,左侧的“删除”按钮会将其删除 问题是,当用户从列表中选择一种样式时,它不会显示为组合框中的选定样式-即,在下拉列表再次折叠/关闭后,样式字段将为空 这是我的代码: 啤酒视图Javascript 所选ng选项项不存在';不要固守';组合框';,javascript,angularjs,Javascript,Angularjs,我是AngularJS的新手,正在努力做一些应该很容易的事情 我有一个难看的页面: 用户在此屏幕上添加新的啤酒,啤酒可能有多种风格-因此“添加”按钮会创建一个新的“风格”组合框,左侧的“删除”按钮会将其删除 问题是,当用户从列表中选择一种样式时,它不会显示为组合框中的选定样式-即,在下拉列表再次折叠/关闭后,样式字段将为空 这是我的代码: 啤酒视图 <div class="form-group" ng-repeat="style in beer.styles">
<div class="form-group" ng-repeat="style in beer.styles">
<label for="style" class="col-sm-1 control-label" ng-if="$index == 0" >Style</label>
<div class="col-sm-1" ng-if="$index > 0">
<button type="button" class="btn btn-danger" ng-click="removeStyle($index)">Remove</button>
</div>
<div class="col-sm-10">
<select class="form-control"
ng-controller="styleCtrl"
ng-model="selectedStyleId"
ng-options="style.id as style.name for style in styles"
ng-change="updateStyle($index, selectedStyleId)">
</select>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-primary" ng-click="addNewStyle()">Add</button>
</div>
</div>
啤酒控制器
.controller('beerCtrl', ["$scope", "$location", function ($scope, $location) {
$scope.beer = {
'styles': [
{ 'id' : '-1' }
]
}
$scope.addNewStyle = function() {
$scope.beer.styles.push({ 'id': '-1' });
}
$scope.removeStyle = function(index) {
$scope.beer.styles.splice(index, 1);
}
$scope.updateStyle = function(index, styleId) {
$scope.beer.styles[index] = { 'id': styleId };
}
数组中的styleId设置正确,唯一的问题是屏幕
你发现我的代码有什么错误吗
注:我怀疑我在同一个视图中有两个控制器——BeerController和一个“嵌套”的StyleController可能与根本原因有关 正如我提到的,我是AngularJS的新手,所以我的错误很简单。我没有使用on change,而是将所选值直接绑定到backing对象:
<select class="form-control"
ng-controller="styleCtrl"
ng-model="beer.styles[$index].id"
ng-options="style.id as style.name for style in styles">
这就完成了任务。愚蠢的疏忽
<select class="form-control"
ng-controller="styleCtrl"
ng-model="beer.styles[$index].id"
ng-options="style.id as style.name for style in styles">