Access the value of a specific field within an object using ng-options and use it to filter out other

I have created two separate lists.

1) The first list contains the service names.

2) The second list contains the product names assigned to each service name.

Each product has a unique ID that matches it with its corresponding service.

app.controller('loadProductServicesCtrl',function($scope){
    $scope.services = [
        {"ServiceID": 1, "ServiceName": "Telecommunications"},
        {"ServiceID": 2, "ServiceName": "Energy"},
        {"ServiceID": 3, "ServiceName": "Private Health Insurance"}
    ];

    $scope.products = [
        {
            "ProductID": 9,
            "ServiceID": 1,
            "ServiceName": "Telecommunications",
            "ProductName": "Business 500",
            "ProductProfit": 40,
            "ProductTooltip":""
        },
        {
            "ProductID": 10,
            "ServiceID": 2,
            "ServiceName": "Telecommunications",
            "ProductName": "Business 1000",
            "ProductProfit": 50,
            "ProductTooltip": ""
        },
        { 
            "ProductID": 11,
            "ServiceID": 3,
            "ServiceName": "Telecommunications",
            "ProductName": "Business W",
            "ProductProfit": 75,
            "ProductTooltip": ""
        }
    ];
});
<div class="form-group">
  <label for="selectpicker" class="margin-r-5 form-label">Select Service</label>
  <select data-ng-model="myService" data-ng-options="service as service.ServiceName for service in services" class="selectpicker services">
      <option value="">Select Service</option>                
  </select> 
</div>

<div class="form-group products">
  <div class="checkbox checkbox-primary checkbox-inline" ng-repeat="x in products">
    <input type="checkbox" id="{{ x.ProductID }}" value="option1">
    <label for="{{ x.ProductID }}"> {{ x.ProductName }} </label>
  </div>
</div>

I am trying to filter the products based on the selected service ID. I attempted to use the ng-model on the select element, but it doesn't seem to be working correctly. Do you have any advice on how to achieve this?

Answer №1

You need to follow these steps:

ng-repeat="x in products|filter:{ServiceID:myService.ServiceID}"

Snippet in Action

var app = angular.module('app', []);

app.controller('loadProductServicesCtrl', function($scope) {
  $scope.services = [{
    "ServiceID": 1,
    "ServiceName": "Telecommunications"
  }, {
    "ServiceID": 2,
    "ServiceName": "Energy"
  }, {
    "ServiceID": 3,
    "ServiceName": "Private Health Insurance"
  }];
  $scope.products = [{
    "ProductID": 9,
    "ServiceID": 1,
    "ServiceName": "Telecommunications",
    "ProductName": "Business 500",
    "ProductProfit": 40,
    "ProductTooltip": ""
  }, {
    "ProductID": 10,
    "ServiceID": 2,
    "ServiceName": "Telecommunications",
    "ProductName": "Business 1000",
    "ProductProfit": 50,
    "ProductTooltip": ""
  }, {
    "ProductID": 11,
    "ServiceID": 3,
    "ServiceName": "Telecommunications",
    "ProductName": "Business W",
    "ProductProfit": 75,
    "ProductTooltip": ""
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="loadProductServicesCtrl">
  <div class="form-group">
    <label for="selectpicker" class="margin-r-5 form-label">Select Service</label>
    <select data-ng-model="myService" data-ng-options="service as service.ServiceName for service in services track by service.ServiceID" class="selectpicker services">
      <option value="">Select Service</option>

    </select>
  </div>
 Selected Id : {{ myService.ServiceID}}
  <div class="form-group products" ng-repeat="x in products|filter:{ServiceID:myService.ServiceID}">
    <div class="checkbox checkbox-primary checkbox-inline">
      <input type="checkbox" id="{{ x.ProductID }}" value="option1">
      <label for="{{ x.ProductID }}">{{x.ProductName}}</label>
    </div>
  </div>
</div>

Answer №2

Apply a filter within the ng-repeat directive

ng-repeat="item in items | filter:{ PropertyID: myProperty.PropertyID }"

See an example here: https://jsfiddle.net/vorant/m330mp3a/

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

Is there a way to set the default timezone for the entire application to something like 'UTC' using JavaScript and Angular?

I'm currently developing a Hotel application where customers communicate using UTC. I have completed most of the work but everywhere I used the date object like so => new Date(). Before running the application, I need to change my local timezone to ...

Puppeteer's flawed performance leads to the generation of low-quality

Currently, I am utilizing puppeteer to generate a PDF from my static local HTML file. However, the resulting PDF is turning out to be corrupted. When attempting to open the file using Adobe Reader, an error message pops up stating 'Bad file handle&apo ...

Trouble displaying JSON data with AngularJS $http service

Struggling to retrieve json data. Initially, I created an ajax request that functioned properly in a regular html page but failed in my angular app. As a result, I decided to experiment with the built-in $http get function. Surprisingly, no errors are thro ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Guide to implementing a datepicker on a webpage using Laravel

I am having trouble displaying the datepicker using the code below in my Laravel 4.2 application on Firefox. Is there a better way to display datepickers? Are there any CDNs available for this purpose? <table class="table table-striped"> <t ...

Sending a message from a Vue.js application to Contact Form 7 using the Wordpress REST API - a step-by-step guide

I recently added Contact-Form-7 to my WordPress admin panel, which generated an API Endpoint for me at http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms Attempting to send a POST request to this endpoint using the following code: data() ...

Using AngularJS to send a 2D array via POST request

How to use Angular HTTP POST $http({ contentType: "application/json; charset=UTF-8", url: "myCSharpMethod", method: "POST", data: myData, // 2D array ( myData[[],[]] ) traditional: true }) .success ...

Storing sound recordings with GridFS

I am currently facing an issue with the following code, it is only working partially and I require assistance in fixing it. The function saveAudioToGridFS() should return a file ID to its calling function. Despite verifying that the value to be returned ...

Tap, swipe the inner contents of a <div> element without being inside it

(Make sure to check out the image below) I'm facing an issue with a <div> on my website. It's not taking up the full width of the page, and the scrolling functionality within the <body> is not working as expected. I just want the cont ...

Is there a way to modify this within a constructor once the item has been chosen from a randomly generated array?

If I use the following code: card01.state = 3; console.log(card01); I can modify the state, but I'm interested in updating the state of the card chosen by the random function. class Item { constructor(name, state) { this.name = name; thi ...

Is it possible to dynamically set the maximumSelectionLength in a select2 dropdown?

In my HTML, I have two select elements. One is for multiple selection of items in a dropdown and the other is for adding tags. If the number of selected items is 3, then users should only be allowed to add 3 tags - no more and no less. $(".js-example-b ...

Ajax: Failed to send POST request (404)

After adding a POST script in the manage.ejs file and console logging the data to confirm its functionality, I encountered an issue. Below is the code snippet: <script type="text/javascript"> var guildID = "<%= guild.id %>"; let data = {so ...

Delay in Response of OnTextChanged Event in ASP.NET

The functionality is there, but it doesn't respond immediately. It only works when I click on something. I attempted using the onkeyPress method as well: <asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress" ></asp:TextBox& ...

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...

Dealing With HttpClient and Asynchronous Functionality in Angular

I've been pondering this issue all day. I have a button that should withdraw a student from a class, which is straightforward. However, it should also check the database for a waiting list for that class and enroll the next person if there is any. In ...

AngularJS ng-repeat filter allows you to display a specific set of data

Having some issues with a filter, my code looks something like this: <tr ng-repeat="data in dataset | filter:{id:12}"> <td>{{data.id}}</td> <td>{{data.name}}</td> </tr> I am interested in filtering by an ...

Troubleshooting Problem with Custom Class Buttons in Angular Material

Recently, I've been working on creating a custom class for angular material buttons. However, I encountered an issue where the button fades out or turns white when I click on it and then navigate away from the browser window (minimize it or activate a ...

Obtain the breakpoint value from Bootstrap 5

We have recently updated our project from Bootstrap 4 to Bootstrap 5. I am trying to retrieve the value of a breakpoint in my TypeScript/JavaScript code, which used to work in Bootstrap 4 with: window .getComputedStyle(document.documentElement) .g ...

JavaScript is failing to update the table values as users interact with it

I've created an HTML table and used PHP to populate the values. The goal is to allow users to update order statuses with a status and message input. Initially it works fine, but after multiple uses, it either updates the wrong row or doesn't up ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...