Filtering ng-options with a specific property

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>

Answer №1

If you want to watch a selected option and make changes to the currentItem list based on that selection, remember that ngChange expression is specifically used for evaluating changes in input value, not for changing option values.

$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];
});

Check out this Jsfiddle Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

What is the best way to prevent a package from being linked in React Native?

My current process for adding a module involves using: npm i --save <package_name> After that, I typically run: react-native link instead of specifying the package name, which links all possible react native libraries listed in my package.json file. ...

Does Protractor have a logging feature that will integrate log invocations into the control-flow?

Can Protractor log functions be used to add log invocations to the control-flow? Is there a feature that allows me to access and utilize the control-flow directly? It seems like console.log logs outside of the control-flow, which may not always be ideal. ...

Using the Chromecast SDK to stream content with m3u8 URLs

After setting up the webserver that is included in the SDK (https://github.com/googlecast/), I tested it with the provided example media file, which worked perfectly. However, when attempting to use an example m3u8 file, it resulted in the following error: ...

A guide to implementing SSR layout using Next-Auth

Currently, I am facing an issue in my project where the session is being automatically set to client-side. However, when I build the project, the page remains dynamic with the client-side session. If I remove the next-auth project, the page switches to SSR ...

Issue: Attempting to display array elements within a React Functional Component?

Encountering an issue while attempting to log array elements, receiving the error message: TypeError: Cannot read property '0' of undefined Interestingly, I am able to successfully log the project.tasks array object in the console. However, l ...

Adding miscellaneous PHP scripts

When a user clicks on the sample button, my PHP code gets appended. It works fine, but I want to clean up my process. After some research, I learned that using jQuery AJAX is the way to go. The only problem is, I'm not sure how to implement AJAX. I&ap ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

Switching the class for the pseudo-element :after

Consider a scenario where there is a button: <button href="#" class="search no-style search-active" style="display: inline-block;"> <div class="pointer" style="display:none">::after</div> </button> Upon activation of the button, ...

TypeScript is unable to locate the identifier 'async' within the code

While working with TypeScript, I encountered an error: [ts] Cannot find name 'async' Here is the code snippet causing the issue: async someAsyncCode() { let asyncFn = () => { return new Promise((resolve: Function) => { resolv ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

The behavior of Daterangepicker varies when using callback functions versus applying the daterangepicker

Encountered an issue with the daterangepicker recently. There is a form that needs to be submitted whenever a user selects a new date range. The problem arises when using the daterangepicker callback - even though the correct values for the newly selected ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

ngIf not recognizing dynamically assigned variables

I'm having a code snippet that looks like this ng-show="!edit{{id}} && imageUrl" However, it doesn't seem to be working. On the other hand, ng-show="!edit1 && imageUrl" works perfectly fine. Could there be an issue with the s ...

Oops! Looks like the Digest is already being processed

I encountered the following issue: Error: [$rootScope:inprog] $digest already in progress http://errors.angularjs.org/1.2.16/$rootScope/inprog?p0=%24digest I'm uncertain about the root cause of this problem or what the terms "apply" and "digest" ...

Generating thick, shadowed lines in three.js to represent layers in a 3D printing visualization

I've been exploring ways to add depth to lines in Three.js that can cast shadows and appear as solid objects, but so far I've only achieved thicker lines that lack the 3D look I'm aiming for. This is for an online 3D printing platform where ...

Having trouble with Redux asynchronous operation while trying to access the current state?

Having some asynchronous issues with getting the state in my component. It's working fine when I console log in mapStateToProps, but for some reason it shows the old state when I console log inside render function. Any ideas on how to properly chain f ...

Include multiple connections between two points in an amCharts force-directed network

I'm currently utilizing the amcharts force directed network to display a knowledge graph. Within this knowledge graph, it's possible for two nodes to have multiple edges in both directions. For instance: A "person" could be linked as "born in" ...

How can we combine refs in React to work together?

Let's consider this scenario: I need a user to pass a ref to a component, but I also have to access that same ref internally. import React, { useRef, forwardRef } from 'react'; import useId from 'hooks/useId'; interface Props ext ...