Angular JS for Mutually Exclusive Selections

时间:2014-05-26 20:13:49

标签: angularjs

我有两个选择标记,每个标记都有相同的选项。我的目标是在另一个选项上选择一个不可选择的选项。鉴于我使用了一系列对象作为选项的来源:[{name:' one'},{name:' two'},{name:' 3'}]

1。默认值。

选择1 - 一个 - 两个 - 三个

选择2 - 一个 - 两个 - 三个

2。选择1被选中。

选择1 - 一个 - 两个 - (3)

选择2 - 一个 - 两个

第3。选择2被选中。

选择1 - 两个 - (3)

选择2 -(一) - 两个

1 个答案:

答案 0 :(得分:4)

FIDDLE

您可以使用自定义过滤器功能过滤掉已选择的选项。

<select ng-model="picks.select1">
     <option ng-repeat="option in options | filter:optionFilter(picks.select1)" ng-value="option.name">

此函数将select的模型作为参数,以便能够将其显示为仍可选择。

 $scope.optionFilter = function(selectedOptionModel){
    return function(option){
       //actual filtering function starts here, angular passes all items in the array
       // to this function and filters out the ones you returned false

       if(option.name === selectedOptionModel) return true;  // if it's already the selected option it should still be an option in the dropdown
        else{
            for(var key in $scope.picks){
                //otherwise we check to see if they are picked in 
                //another select dropdown and immediately return false because
                // that option is elected should be filtered out.
                if(option.name===$scope.picks[key]) return false;
            }
            //if we successfully got out of the loop it means it's not selected so return true
            return true;
        }
    }
}