2017-02-24 15 views
2

我的要求是有多個選擇框具有相同的下拉列表(ng-options)數組,但是如果我在一個選擇框中選擇一個值,則應從其他選擇框下拉列表中刪除它。選擇框的角度不可變陣列

在on change事件中,我試圖創建一個新的數組,但不包括爲第一個數組選擇的項目。但它會從兩個選擇框中刪除。就像一個不可變的DS總是返回一個原始的變異克隆。

上需要的建議是有可能實現這種方式還是有辦法解決它

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    
 
    $scope.items = []; 
 
    $scope.selectedItem = { name: 'two', id: 27 }; 
 
    $scope.items = [{name: 'one', id: 30 },{ name: 'two', id: 27 },{ name: 'threex', id: 50 }]; 
 
    $scope.remove=function(data){ 
 
    $scope.items=$scope.items.filter(item=>{ 
 
      return item.name!==data.name; 
 
    }); 
 
    
 
});
<!-- begin snippet: js hide: false console: true babel: false -->

<!DOCTYPE html> 
<html ng-app="plunker"> 

    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script data-require="[email protected]" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="app.js"></script> 
    </head> 

    <body ng-controller="MainCtrl"> 


    <select ng-model="selectedItem" ng-change="remove(selectedItem)" ng-options="item.name for item in items track by item.id"></select> 


    <select ng-model="selectedItem1" ng-options="item.name for item in items track by item.id"></select> 

    </body> 
</html> 
$scope.remove=function(data){ 
    $scope.items=$scope.items.filter(item=>{ 
      return item.name!==data.name; 
    }); 

回答

2

我建議在ng-options語法中使用過濾器管道。 看一看plunker

<select ng-model="selectedItem1" ng-options="item.name for item in items | filter: coolFilter1"></select> 

     <select ng-model="selectedItem2" ng-options="item.name for item in items | filter: coolFilter2"></select> 
1

只要你是在兩個選擇框中使用items,在012上進行更改數組將在兩個選擇框中反映出來。爲選擇框使用單獨的數組,或者找到一種方法來過濾掉第一個選擇框中的項目。例如,您可以在第一個選擇框中的選定項目上設置selected=true,然後通過將篩選器!selected添加到ng-options,在第一個選擇框中過濾掉items。這樣你可以在兩個盒子上使用相同的items陣列。

1

當您使用ES6箭頭功能時,您不需要寫'返回'。

$scope.items=$scope.items.filter(item => item.name !== data.name); 

$scope.items=$scope.items.filter重新分配看起來奇怪..這將是最好不要改變源對象。


您可以給$ scope.items中的每個對象一個布爾值,然後在視圖中對其進行過濾。

ng-options="item.name for item in items track by item.id | filter:{'isUsed': false}"