Angularjs 如何选择角度过滤后的第一个选择选项

Angularjs 如何选择角度过滤后的第一个选择选项,angularjs,Angularjs,我有一个带过滤器的select。过滤后,从列表中删除所选项目,并添加第一个空选项项目。应采取什么措施来选择第一个可用选项?以下是标记: %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' => 'd

我有一个带过滤器的
select
。过滤后,从列表中删除所选项目,并添加第一个空
选项
项目。应采取什么措施来选择第一个可用选项?以下是标记:

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

在使用指令进行过滤后,我没有管理如何设置默认值,因此在控制器中使用$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!'}
-

改变

%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in devices | filter:search'}

你将在你的范围内过滤出你想要的任何设备 具体来说,您可以观察它,并在它发生变化时设置所选设备

$scope.$watch('filtered_devices', function(value){
  if (filtered_devices) {
    $scope.device = filtered_devices[0];
  }
}, true);
所以你不必再过滤了

更新:

在使用我建议的模型之后,我发现使用过滤器表达式作为ng选项的源可能是个坏主意。我假设原因是,每次对过滤器求值时,它都返回一个新集合,因此diget循环得出结论,它是脏的,需要重新绑定或其他什么


我现在使用的是一种不同的模式,在我的
$scope
中有一个
筛选的\u items
集合,我通过过滤器输入上的“ng change”来更新它。因此,ng选项绑定到的
过滤的\u项
不会更改,除非它确实需要更改

另一种解决方案,它不使用
$watch
,而是使用
ng change

还添加了
debounce
,以便它仅在1000毫秒后调用
ng change

看法

%选择{'ng-model'=>'device','ng options'=>'device.serial_number for devices 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];
};

你能分享更多的代码或设置一个Plunk Pleases吗?我的问题兄弟,你找到什么了吗?@themis,我用控制器内的$watch完成了这项工作,看到答案了。嗯。。。如果不再次应用筛选器,是否无法获取筛选列表?谢谢,这种方式看起来更好。
$scope.$watch('filtered_devices', function(value){
  if (filtered_devices) {
    $scope.device = filtered_devices[0];
  }
}, true);
$scope.filtered_devices = [];
$scope.updateDevices = function () {
    if ($scope.filtered_devices.length === 0) return;
    $scope.device = $scope.filtered_devices[0];
};