我有select
过滤器。过滤Angular后,会从列表中丢失所选项目,并添加第一个空option
项。应该怎样做才能选择第一个可用选项?这是标记:
%select{'ng-model' => 'search.device_type_id', 'ng-options' => 'type.id as type.product_name for type in device_types'}
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in devices | filter:search'}
答案 0 :(得分:3)
更改
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in devices | filter:search'}
到
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in filtered_devices=(devices | filter:search)'}
您将在您的范围内使用filtered_devices来处理您想要的内容 特别是你可以观看它并在它改变时设置所选设备
$scope.$watch('filtered_devices', function(value){
if (filtered_devices) {
$scope.device = filtered_devices[0];
}
}, true);
所以你不必再过滤......
更新:
在使用模型后,我建议我发现将过滤器表达式作为ng-options的来源可能是一个坏主意。我假设原因是每次评估过滤器时它返回一个新的集合,因此diget周期断定它是脏的并且需要重新绑定或其他。
我现在使用的是另一种模式,我在filtered_items
中有一个$scope
集合,我通过过滤器输入上的“ng-change”更新它。所以绑定ng-options的filtered_items
不会改变,除非实际需要改变......
答案 1 :(得分:0)
我没有管理如何在使用指令过滤后设置默认值,所以在控制器中使用$ watch执行此操作,如下所示:
# View.haml
-# select itself
%select{'ng-model' => 'search.brand_id', 'ng-options' => 'brand.id as brand.name for brand in brands'}
%select{'ng-model' => 'search.device_type_id', 'ng-options' => 'type.id as type.product_name for type in device_types | filter:search.brand_id'}
%select{'ng-model' => 'device', 'ng-required' => 'true', 'ng-options' => 'device.serial_number for device in devices | filter:search'}
-# selected device
%input{'ng-model' => 'selectedDevice.id', type: 'text', disabled: true, placeholder: 'Select a device!'}
-
#Controller.js
$scope.$watch('search.device_type_id', function(value){
var filtered_devices = $filter('filter')($scope.devices, $scope.search);
if (filtered_devices) {
$scope.device = filtered_devices[0];
}
}, true);
答案 2 :(得分:0)
另一个不使用$watch
但使用ng-change
还添加了debounce
,以便在1000毫秒之后只调用ng-change
视图
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in filtered_devices=(devices | filter:search)', 'ng-change' => 'updateDevices()', 'ng-model-options' => '{ debounce: 1000 }'}
控制器
$scope.filtered_devices = [];
$scope.updateDevices = function () {
if ($scope.filtered_devices.length === 0) return;
$scope.device = $scope.filtered_devices[0];
};