基于属性的ng-options过滤

时间:2015-04-19 16:09:35

标签: javascript angularjs ng-options

基本上我是java开发人员最近切换到javascript(AngularJs)编码所以我对javascript / AngularJS很新。 在我编码时,我遇到了一个案例,如果我必须展示 如前所述:只有水果套/只有蔬菜或两者都根据所选择的下拉菜单当前正在做的有一个" fruitNVeg"包含所有项目并具有临时变量的数组" currentItems"在任何情况下,根据所选项目过滤掉所需的项目,例如仅限水果/仅蔬菜/两者。

现在我的问题是 有什么方法可以使用" fruitNVeg"本身在HTML中,并说只显示其"显示" property设置为true。 即,在不使用额外变量的情况下获得相同的功能" currentItems"。

另外,如果可能的话,请根据行数来优化我当前的逻辑 我厌倦了在任何地方创建2个阵列(完成+过滤): - (

FruitsController.js
     $scope.fruitNVeg = [
                       { id : 1, name : "mango" , show : true , cat : "F"},
                       { id : 2, name : "orange", show : true , cat : "F"},
                       { id : 3, name : "tomato", show : true , cat : "F"},
                       { id : 4, name : "brinjal",show : false , cat : "V"},  
                       { id : 4, name : "potato", show : false , cat : "V"},
                       { id : 4, name : "ginger", show : false , cat : "V"}, 
                       ];

   $scope.selectList = [ 
                         {id:1, name  : "Fruits Only" },
                         {id:2, name  : "Vegetable Only" },
                         {id:3, name  : "Fruits & Vegetable" },
                        ];
    $scope.selectedItem = $scope.selectList[0];                  
    $scope.currentItems = angular.copy($scope.fruitNVeg,$scope.currentItems);
    $scope.selItem = $scope.currentItems[0];

    $scope.onChangeSelecList = function (){
        if(selectedItem.name == "Fruits Only"){
           //Use $filter to populate $scope.currentItems  with fruits only items
        } else if(selectedItem.name == "Vegetable Only"){
          //Use $filter to populate $scope.currentItems  with vegetables only items
        } else {
           $scope.currentItems = angular.copy($scope.fruitNVeg,$scope.currentItems);
        }
        $scope.selItem = $scope.currentItems[0];
    };

FruitDemo.Html
     <label> Please Select what to show <label>
     <select ng-model="selectedItem" ng-options="list.name for list in selectList" ng-change="onChangeSelecList()" name="listDropDown" id="listDropDown"></select>
     <select ng-model="selItem" ng-options="item.name for item in currentItems"  name="itemDropDown" id="itemDropDown"></select>

1 个答案:

答案 0 :(得分:1)

您可以观看选定的选项,并可以相应地更改currentItem list.ngChange表达式用于评估输入值的变化,而不是选项值更改。

$scope.$watch("selectedItem", function(i) {
  $scope.currentItems.length = 0;
  if (i.id === 1) {
    angular.forEach($scope.fruitNVeg, function(val, key) {
      if (val.cat === 'F') {
        $scope.currentItems.push(val);
      }
    });
  } else if (i.id === 2) {
    angular.forEach($scope.fruitNVeg, function(val, key) {
      if (val.cat === 'V') {
        $scope.currentItems.push(val);
      }
    });
  } else {
    $scope.currentItems = $scope.fruitNVeg;
  }
  $scope.selItem = $scope.currentItems[0];
});

Jsfiddle Example