【发布时间】:2015-01-08 03:04:50
【问题描述】:
在 ng-repeat 中使用 ng-model 时,我似乎只实现了一种方式的数据绑定。
目前,如果用户从其中一个下拉菜单中进行选择,则模型会更新。但是由于某种原因,选择没有绑定到模型中的更改。
<body ng-controller="MainCtrl as c">
<table>
<tr ng-repeat="controller in c.data">
<td>
<select ng-model="controller.port" required="" class="form-control form-control-inline">
<option value="">Choose a port</option>
<option value="{{idx}}" ng-repeat="idx in c.pwm" ng-disabled="c.isPWMUsed(idx)">
{{idx}} {{c.isPWMUsed(idx)? 'used' : ''}}
</option>
</select>
</td>
</tr>
</table>
<pre>
{{c.data | json:4}}
</pre>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
this.data = [
{
"port": 1
},
{
"port": "2"
},
{
"port": ""
},
{
"port": "5"
}
];
this.pwm = [0,1,2,3,4,5,6,7,8,9];
this.isPWMUsed = function (n) {
var out = false;
n=n.toString();
for (var i = 0; i < this.data.length; i++) {
if (this.data[i].port === n) {
out = true;
break;
}
}
return out;
};
$scope.gettypeof = function(item){
return (typeof item);
};
});
这是一个笨蛋:http://plnkr.co/edit/QlEP73aZwhjcjRGszbJb?p=preview 注意默认数据是如何预先分配一些端口的。但是,它们似乎没有正确绑定到下拉列表。
-- 编辑--
我没有使用 ng-options 的原因是因为我无法弄清楚如何在选择选项时禁用它们。请注意添加 ng-disabled="c.isPWMUsed(idx)" 添加的功能,使用户无法选择已使用其他下拉菜单之一选择的项目。
-- 编辑 2 --
因此,实际上,问题归结为“有没有办法从ng重复进行选项时进行选择的两种绑定工作?”
另一个相同的情况,使用来自AngularJS docs on select的代码
如果我改变这个标记
<select ng-model="myColor" ng-options="color.name for color in colors">
<option value="">-- choose color --</option>
</select>
到这一点标记
<select ng-model="myColor">
<option value="">-- choose color --</option>
<option value="{{idx}}" ng-repeat="(idx, color) in colors">{{color.name}}</option>
</select>
中间选择的数据绑定停止工作。有没有办法使用 ng-repeat 而不是 ng-options 使数据绑定工作?
-- 编辑 3 --
这段代码似乎工作......
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', function AppCtrl($scope) {
$scope.filterCondition = {
operator: 'eq'
}
$scope.operators = [{
value: 'eq',
displayName: 'equals',
title: 'The equals operator does blah, blah'
}, {
value: 'neq',
displayName: 'not equal',
title: 'The not equals operator does yada yada'
}]
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>
<body ng-app="myApp" ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator">
<option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
<select ng-model="filterCondition.operator">
<option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
<input ng-model="filterCondition.operator">
</body>
【问题讨论】:
标签: javascript angularjs angularjs-ng-repeat