我是AngularJs的新手。我有三个带有ng-options的选择框。在添加过滤器之前它工作正常。
<td style="33%">
<select ng-options="car.BaseStation for car in UnUsedCars | orderBy:'BaseStation'" ng-model="selected.BaseStation">
<option value="">All Locations</option>
</select>
</td>
<td style="33%">
<select ng-options="car.CarType for car in UnUsedCars | filter: selected.BaseStation | orderBy:'CarType'" ng-model="selected.CarType">
<option value="">All Car Types</option>
</select>
</td>
<td style="33%">
<select ng-options="car.Color for car in UnUsedCars | filter: selected.BaseStation | filter: selected.CarType | orderBy:'Color'" ng-model="selected.Color">
<option value="">All Car Colors</option>
</select>
</td>
第二个选择框应根据第一个选择框值进行操作,第三个选择框应根据第一个和第二个选择。
这3个选择的数据来自一组对象'UnUsedCars'。 示例输入如下:
[{
"CarType" : "Audi",
"Color" : "White",
"BaseStation" : "Canada"
},
{
"CarType" : "BMW",
"Color" : "White",
"BaseStation" : "U.S.A"
},
{
"CarType" : "Benz",
"Color" : "Black",
"BaseStation" : "Canada"
}]
我的JS如下
scope.selected = {
BaseStation: null,
CarType: null,
Color: null
};
scope.$watch('selected.BaseStation', function() {
scope.selected.CarType = null;
});
scope.$watch('selected.BaseStation', 'selected.CarType', function() {
scope.selected.Color = null;
});
我在这里犯了什么错误?
答案 0 :(得分:1)
我强烈建议您避免filter
,因为他们会改变您的ngModel.viewModel
(您传递的价值)。
我建议您在select下为ng-show='ctrl.isBaseStation(car)'
写<option>
。
这是一种简单的方法,不需要任何额外的过滤。过滤本身是一个繁重的过程,通过剥离过滤结果来解析所有数据。您想要实现的结果 - 不显示项目,但不改变原始数据集。
P.S。使用ng-show
(隐藏/显示)重新渲染选项比重新计算所有数据集要快得多。
答案 1 :(得分:1)
首先,您不需要使用$watch
或类似的内容。
嗯,实际上您的ngModel
正在从每个<select>
接收一个对象,但由于您只想获取该属性,因此您应该使用as
语法,如下所示:
<select ng-options="car.BaseStation as car.BaseStation for car in UnUsedCars | orderBy: 'BaseStation'" ng-model="selected.BaseStation">
查看代码段:
(function() {
angular
.module('app', [])
.controller('mainCtrl', mainCtrl);
function mainCtrl($scope) {
$scope.UnUsedCars = [
{
"CarType":"Audi",
"Color":"White",
"BaseStation":"Canada"
},
{
"CarType":"BMW",
"Color":"White",
"BaseStation":"U.S.A"
},
{
"CarType":"Benz",
"Color":"Black",
"BaseStation":"Canada"
}
];
}
})();
&#13;
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<table>
<tr>
<td style="33%">
<select ng-options="car.BaseStation as car.BaseStation for car in UnUsedCars | orderBy: 'BaseStation'" ng-model="selected.BaseStation">
<option value="">All Locations</option>
</select>
</td>
<td style="33%">
<select ng-options="car.CarType as car.CarType for car in UnUsedCars | filter: selected.BaseStation | orderBy: 'CarType'" ng-model="selected.CarType">
<option value="">All Car Types</option>
</select>
</td>
<td style="33%">
<select ng-options="car.Color as car.Color for car in UnUsedCars | filter: selected.BaseStation | filter: selected.CarType | orderBy: 'Color'" ng-model="selected.Color">
<option value="">All Car Colors</option>
</select>
</td>
</tr>
</table>
</body>
</html>
&#13;