2015-04-19 146 views
-1

基本上我是java開發人員最近切換到javascript(AngularJs)編碼,所以我完全新的JavaScript/AngularJS。 當我編碼時,我遇到了一個案例,其中,如果我必須顯示 如前所示:僅限水果集合/僅限蔬菜或基於下拉菜單選擇我目前正在做的是「fruitNVeg」數組保存所有物品並且具有臨時變量「currentItems」,其在任何情況下都過濾出所需物品,例如僅水果/蔬菜/兩者都基於所選擇的物品。基於屬性的ng選項過濾

現在我的問題是 有什麼方法可以在HTML中使用「fruitNVeg」本身,並說只顯示「show」屬性設置爲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

,您可以觀看所選的選項,並可以相應地改變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

+0

謝謝Akhlesh :-)不錯,但我問的是不可能沒有使用「$ scope.currentItems」我的意思是在前端使用「$ scope.fruitNVeg」本身,並使用某種過濾器? ,我不知道爲什麼有人會提出我的問題:-( – HkFreaKuser1673718