4

我有一个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'}
4

3 回答 3

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)'}

并且您将在您的范围内拥有 filters_devices 来处理您希望的任何事情

$scope.$watch('filtered_devices', function(value){
  if (filtered_devices) {
    $scope.device = filtered_devices[0];
  }
}, true);

所以你不必再次过滤......

更新:

在使用我建议的模型后,我发现将过滤器表达式作为 ng-options 的源可能是个坏主意。我认为原因是每次评估过滤器时,它都会返回一个新集合,因此数字循环得出结论,它是脏的,需要重新绑定或其他什么。

我现在使用不同的模式,其中我有一个filtered_items集合,$scope我正在通过过滤器输入上的“ng-change”更新它。所以filtered_itemsng-options 绑定的不会改变,除非它真的需要改变......

于 2014-06-25T06:50:08.380 回答
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);
于 2013-08-02T09:19:32.980 回答
0

另一种不使用$watch但使用的解决方案ng-change

还添加debounce了使其仅ng-change在 1000 毫秒后调用

看法

%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];
};
于 2016-03-13T15:02:33.247 回答