2013-07-30 36 views
4

我有一個帶有過濾器的select。過濾後Angular從列表中刪除選定的項目,並添加第一個空的option項目。應該如何選擇第一個可用選項?下面是標記:如何在Angular中過濾後選擇第一個選擇選項

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

你可以分享更多的代碼或設置plunker請 –

+0

同樣的問題老兄,你有沒有設法找到的東西嗎? – themis

+0

@themis,我已經用$ watch在控制器內完成了這個工作,看到了答案。 – lifecoder

回答

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); 

讓你不必須再次過濾...

UPDATE:

與模型的工作後,我建議我發現可能是一個壞的想法有一個過濾器表達式作爲ng-options的來源。我認爲,原因是每次過濾器評估它返回一個新的集合,因此diget循環得出結論,它是骯髒的,需要重新綁定或任何。

我現在正在使用不同的模式,其中我的$scope中有一個filtered_items集合,我正在通過過濾器輸入上的「ng-change」對其進行更新。所以到NG選項勢必不會改變,除非它實際上需要改變filtered_items ...

+0

謝謝,這種方式看起來更好。 – lifecoder

+0

請參閱我的更新... – epeleg

0

我沒有設法如何使用指令過濾後設置默認,所以這樣做與$控制器內看,就像這樣:

# 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); 
+0

嗯...有沒有辦法得到沒有再次應用過濾器過濾列表? – epeleg

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]; 
}; 
相關問題