As a java developer who recently transitioned to coding in javascript (AngularJS), I am new to JavaScript/AngularJS. While working on my code, I encountered a scenario where I needed to display either a set of fruits only, vegetables only, or both based on the selected drop-down option. Currently, I am using an array called "fruitNVeg" which contains all items and a temporary variable called "currentItems" that filters out the required items (fruits only/vegetables only/both) based on the selection.
My question is, is there a way to use the "fruitNVeg" array directly in HTML to display only the items whose "show" property is set to true? In other words, achieve the same functionality without the need for the extra variable "currentItems".
Additionally, if possible, please suggest optimizations to my current logic in terms of reducing the number of lines of code. I'm tired of creating two arrays (complete + filtered) everywhere :-(
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>