我有多个选择标签,每个标签都使用ng-options。它们都显示在相同的项目数组中。但是,当我选择一个项目时,所有选择都会更新到该项目。有办法防止这种情况吗?
<select ng-model="selectedClass" ng-options="className as className for className in classes track">
<option value="" disabled selected>Select Class</option>
</select>
<select ng-model="selectedClass" ng-options="className as className for className in classes track">
<option value="" disabled selected>Select Class</option>
</select>
<select ng-model="selectedClass" ng-options="className as className for className in classes track">
<option value="" disabled selected>Select Class</option>
</select>
答案 0 :(得分:1)
所有select
都会更新,因为它们都引用相同的ng-model
。
如果每个select
都应该是独立的,那么它们必须使用不同的模型:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.classes = ['A', 'B', 'C'];
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<!--selectedClass1-->
<select ng-model="selectedClass1" ng-options="className as className for className in classes">
<option value="" disabled selected>Select Class</option>
</select>
<!--selectedClass2-->
<select ng-model="selectedClass2" ng-options="className as className for className in classes">
<option value="" disabled selected>Select Class</option>
</select>
<!--selectedClass3-->
<select ng-model="selectedClass3" ng-options="className as className for className in classes">
<option value="" disabled selected>Select Class</option>
</select>
<div>selectedClass1: {{selectedClass1}}</div>
<div>selectedClass2: {{selectedClass2}}</div>
<div>selectedClass3: {{selectedClass3}}</div>
</div>
&#13;
如果您正在使用指令,则可以将模型传递到指令的隔离范围:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', MyCtrl])
.directive('mySelect', mySelect)
function MyCtrl($scope) {
$scope.selections = [];
$scope.classes = ['A', 'B', 'C'];
$scope.addSelect = function() {
$scope.selections.push({
selectedClass: null
});
};
$scope.removeSelect = function(index) {
$scope.selections.splice(index, 1);
}
}
function mySelect() {
return {
restrict: 'E',
scope: {
selection: '=',
classes: '='
},
template: '<select' +
' ng-model="selection.selectedClass"' +
' ng-options="className as className for className in classes">' +
'<option value="" disabled selected>Select Class</option>' +
'</select>'
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="selection in selections">
<my-select selection="selection" classes="classes"></my-select>
<button ng-click="removeSelect($index)">Remove</button>
</div>
<button ng-click="addSelect()">Add a select</button>
<div>selections: {{selections}}</div>
</div>
&#13;