AngularJS filter data between two components

When it comes to filtering data, I usually use the following method:

<input type="search" ng-model="searchTable">
<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in $ctrl.rows | filter: searchTable">
      <td>{{ row.firstName }}</td>
      <td>{{ row.lastName }}</td>
    </tr>
  </tbody>
</table>

If the

<input type="search" ng-model="searchTable">
and
<tr ng-repeat="row in $ctrl.rows | filter: searchTable">
are located in separate components, filtering might require a different approach.

You can view a demonstration on this fiddle.

To separate the components, you may need to include an $onChanges() and utilize expression binding like bindings: { onChange: '&' } within the searchComponent. However, implementing this solution completely might be a bit challenging at first.

I hope this helps clarify things for you. Let me know if you have any further questions.

Answer №1

Click here to see the functional fiddle. The search term is stored in the parent component and passed down to both child components.

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

app.controller('appController', function() {
this.searchTerm = "";
});

app.component('searchComponent', {
template: `
  <h4>{{ $ctrl.title }}</h4>
    <label>Search table</label>
    <input type="search" ng-model="$ctrl.searchTerm">
  `,
  controller: function() {
  this.title = 'Search Component';
  },
  bindings: {
  searchTerm: "="
  }
});

app.component('tableComponent', {
template: `
  <h4>{{ $ctrl.title }}</h4>
    <table>
    <thead>
      <tr>
        <th>First Name</th>
          <th>Last Name</th>
        </tr>
      </thead>
    <tbody>
      <tr ng-repeat="row in $ctrl.rows | filter: $ctrl.searchTerm">
        <td>{{ row.firstName }}</td>
          <td>{{ row.lastName }}</td>
        </tr>
      </tbody>
    </table>
  `,
  controller: function() {
 this.title = 'Table Component';
    
    this.rows = [
    {firstName: 'Zulu', lastName: 'Apple'},
      {firstName: 'Alice', lastName: 'xRay'},
      {firstName: 'Fred', lastName: 'Rogers'}
    ];
  },
  bindings: {
  searchTerm: "<"
  }
});
body {
  font-family: 'Arial', sans-serif;
}
table {
  border-collapse: collapse;
}
td, th {
  border: 1px solid grey;
  padding: 5px;
}
label {
  display: block;
}
input {
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="appController">
    <h3>Filter Between Components</h3>
    <search-component search="searchTerm"></search-component>
    <table-component search="searchTerm"></table-component>
  </div>
</div>

Answer №2

If you want to establish communication between components, you can utilize the emit - on method. The following code demonstrates how you can implement this. Don't forget to have a look at the updated jsfiddle for a working example of the scenario.

Search Component Controller:

$scope.$watch('searchTable', function() {
  $rootScope.$emit('onEmitSearchData', $scope.searchTable);
});

Table Component Controller:

$rootScope.$on('onEmitSearchData', function(event, data) {
  $scope.searchTable = data;
});

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 is the best way to dynamically update a state that is deeply nested?

Is there a way to update the object using key: 1311 and retrieve the updated state while not knowing its exact location but only its key value? state = { iow: [ { key: 1, iow_description: "EARTH WORK", unit: null, rate: nul ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Unusual behavior of leaflet maps in terms of size and tiling arrangements

Currently, I am in the process of integrating a leaflet map into my meteor-based website that utilizes blaze as its templating engine. I have encountered some peculiar issues regarding the map size and its behavior when dragging and zooming. The map init ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

Is there a way to implement a JavaScript || operator alongside ng-class in AngularJS?

I am attempting to apply a class in this way: ng-class="{fa-disabled: cursorWait || wos.wordFormRowIsDisabled(wf)}" I want the fa-disabled class to be included if either cursorWait is true or if the wos.wordFormRowIsDisabled function returns true. Howev ...

Methods for hiding and showing elements within an ngFor iteration?

I am working on an ngFor loop to display content in a single line, with the option to expand the card when clicked. The goal is to only show the first three items initially and hide the rest until the "show more" button is clicked. let fruits = [apple, o ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Can CSS be used to create drop down menus?

Is it possible to create a dropdown menu using only CSS, similar to what you would find in most applications? I have a simple menu bar at the top of my screen and I want to be able to hover over an item like "Item1" and see sub-items appear below it. I en ...

Sorting in MongoDB can be done easily using the $sort operator,

Is it possible to arrange elements based on a given array? For example: const somes = await SomeModel.find({}).sort({'_id': {'$in': [ObjectId('sdasdsd), ObjectId('sdasdsd), ObjectId('sdasdsd)]}}).exec() I am seeking a ...

What is the process for populating a checkbox with data from a configuration file using JavaScript?

I have a requirement where I need to populate a list of checkboxes with data from a configuration file. To elaborate, if my checkboxes are meant to select sports, within my JSON configuration file I have an array like this: sports: ["Tennis", "Rugby", "S ...

Unraveling a binary file to an mp3 format with the power of Node.js

When attempting to encode an MP3 file to Base64 in Node.js using the following method: encodebase64 = function(mp3file){ var bitmap = fs.readFileSync(mp3file); var encodedstring = new Buffer(bitmap).toString('base64'); fs.writeFileS ...

Retrieving the current date in React from a distinct date format

Does anyone know how to retrieve today's date in the following format using React? "2019020420" I have a function that currently retrieves the current date. How can I modify it to output the desired date format shown above? getCurrentDate( ...

Using PHP and MySQL to create checkboxes populated with data retrieved from a database, and then submitting two parameters

Hey there, I've been struggling with this issue for quite some time. I'm trying to create a list with checkboxes populated from a database that includes [checkbox of car id and value][brand][model]. The goal is to select two cars from the list, ...

Localhost Firebase authentication with Facebook integration

I am currently working on a Vue.js app that integrates Firebase for authentication, specifically with the Facebook provider. Despite configuring my Firebase code correctly, I continue to encounter the "Can't load URL: The domain of this URL isn't ...

Navigating through jSON in Angular using iteration

Struggling with using Angular to loop through city names from a JSON file in MongoDB. Need help extracting only the citynames. The JSON data stored in MongoDB looks like this: { "_id" : ObjectId("592409faf1f5831ca882ad39"), "city" : "Aalsmeer", "phone ...

Copying a class and adding the second item in the duplicated class

I have been working with an ajax function to retrieve names from the database. The issue arises when there are multiple names returned - I split them and then attempt to clone the first class in order to display the additional names. However, this proces ...

The property 'hasClass' cannot be retrieved from an undefined or null reference

I'm currently utilizing the AngularJS framework and implementing 'hasClass' within jQuery to create a dropdown on mouse over. The functionality works smoothly in Chrome and Firefox, but I encounter an error in IE stating "Unable to get Prope ...

Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option. Currently, I am utilizing this "plugin": Issue: The problem lies in the plugin not fetching the text value from the <div> element and failing to draw coun ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Is there a way for me to include a prefix in the path where Vue pulls its component chunks from?

I recently incorporated VueRouter into my project and encountered an issue with the asset URL not being correct. Instead of displaying www.example.com/js/0.main.js The URL it generates is www.example.com/0.main.js Any suggestions on how to include the ...