Using NgTable to sort and filter selections

I am working with two select elements. The first select is populated with names, and I would like the second select to only display the ages corresponding to the selected name.

For example:

If I select Jacob in the first select, I want the Age select to only show 27 as an option.

Here is a demonstration on Plunker.

<table ng-table="tableParams" show-filter="true" class="table">
    <tr ng-repeat="user in $data" ng-class="{ 'emphasis': user.money > 500 }">
        <td data-title="'Name'" filter="{ 'name': 'select' }" filter-data="names($column)">
            {{user.name}}
        </td>
        <td data-title="'Age'" filter="{ 'age': 'select' }" filter-data="ages($column)">
            {{user.age}}
        </td>
    </tr>
</table>

I am looking for a way to dynamically filter the options in the second select based on the selection made in the first select element. How can I achieve this?

Answer №1

Check out this demo link: http://plnkr.co/edit/3tLixkFKYgpXfx04PbaD?p=preview

Custom templates can be a useful approach for creating filters. By creating custom templates, you gain full control over the arrays that the filters are connected to and can easily add change events:

<script type="text/ng-template" id="ng-table/filters/name.html">
  <select ng-options="name.id as name.title for name in nameOptions" 
          ng-model="params.filter()['name']" 
          ng-change="ages(column, params.filter()['name'])">
  </select>
</script>
<script type="text/ng-template" id="ng-table/filters/age.html">
  <select ng-options="age.id as age.title for age in ageOptions" 
          ng-model="params.filter()['age']"></select>
</script>

After creating the templates, integrate them into your ng-table markup like this:

<td data-title="'Name'" filter="{ 'name': 'name' }" filter-data="names($column)">
  {{user.name}}
</td>
<td data-title="'Age'" filter="{ 'age': 'age' }" filter-data="ages($column)">
  {{user.age}}
</td>

To populate the option arrays, you can utilize your current names and ages functions:

$scope.names = function(column) {
    ...

    $scope.nameOptions = names;

    ...
};


$scope.ages = function(column, name) {      
  var def = $q.defer(),
      arr = [],
      ages = [];
  angular.forEach(data, function(item) {
      if (inArray(item.age, arr) === -1) {
          if (angular.isUndefined(name) || item.name === name) {
            arr.push(item.age);
            ages.push({
                'id': item.age,
                'title': item.age
            });
          }
      }
  });

  $scope.ageOptions = ages;

  def.resolve(ages);
  return def;
};

Answer №2

I attempted to tackle this issue. Please confirm if it meets your requirements.
DEMO: Fiddle

<body ng-app ng-controller="AppCtrl">
<select ng-model="selectedName" ng-options="item as item for item in name">
    <option value="">Select Name</option>
</select>
<pre>selectedItem: {{selectedName | json}}</pre>

<select ng-model="selectedage" ng-options="item as item for item in age">
    <option ng-if="!selectedage" value="">Select age</option>
</select>
<pre>selectedItem: {{selectedage | json}}</pre>
</body>

JS:

function AppCtrl($scope) {

$scope.name = ["Ved", "James", "Doe","Prakash" ];
var age = {Ved :["25"],James :["26"],Doe:["27"],Prakash:["28"]};
    $scope.$watch('selectedName', function(newValue, oldValue) {
      if ( newValue) {
            var name = $scope.selectedName;
  $scope.age = age[name];
    }
  });
}

Answer №3

Check out this demo: http://plnkr.co/edit/5fvtiept6M6VpAmo8a5f?p=preview. You can use the value selected in the first dropdown as a filter for the second dropdown.

Alternatively

You can bind the selected value from the first dropdown, which is "formData.name" in this example, to the second dropdown.

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <script data-require="ng-table@*" data-semver="0.3.0" src="http://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.js"></script>

    <link data-require="ng-table@*" data-semver="0.3.0" rel="stylesheet" href="http://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.css" />
    <link data-require="bootstrap-css@*" data-semver="3.0.0" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>

<body ng-app="main" ng-controller="DemoCtrl">
    <table ng-table="tableParams" show-filter="true" class="table">
      <tr>
            <td data-title="'Name'">
              <select name="name" 
                data-ng-model="formData.name"
                ng-options="user.name for user in $data" 
                ng-change="changeAge(formData.name)"
                required >
                    <option value="">Select</option>
                </select>
            </td>
            <td data-title="'Age'">
                <select name="age" data-ng-model="formData.age"
                >
                  <option value="">Select</option>
                  <option value="">{{formData.name.age}}</option>
                </select>
            </td>
            </tr>
            <tr ng-repeat="user in $data|filter:formData.name">
              <td>
                {{user.name}}
              </td>
              <td>
                {{user.age}}
              </td>
            </tr>
    </table>    
</body>
</html>

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

The loading GIF in jQuery is malfunctioning when displayed simultaneously on multiple div elements

I am currently working on my Laravel dashboard's blade to showcase various statistics. These stats will be updated whenever the date picker is changed. Below is the code for my date picker: <div class="row"> <div class=&qu ...

What is the most effective way to construct this array?

I have an array of objects that contain multiple properties: [ { a: 3, b: 2, c: 5, d: 6, e: 8 }, { a: 1, b: 5, c: 3, d: 1, e: 2 } ] My goal is to extract only the values of specific properties and create a new array without the objects. For example, ...

The JavaScript syntax dollar sign

I am currently studying a JavaScript source code and it's my first time writing JavaScript. I find some of the syntax confusing. <script id="source" language="javascript" type="text/javascript"> $(function () { window.onload=function() ...

Passing JSON Data Between Functions within an Angular Controller

In my current setup using Node.js, Angular, Express, and HTML, I have a text area that gets filled with formatted text data for letters when certain buttons are clicked. <div class="form-group"> <label class="control-label" for="flyer descriptio ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Encountering difficulty when trying to establish onclick functionality on dynamically loaded table through

Currently, I am working on a website where I am building a timeline using AJAX. I encountered an issue while trying to set the onclick event on each table row. I initially used a class selector but it did not produce any effect. After reading a post on St ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

The function's name has been obscured by the name of its parameter

Caution: ECMAScript 5 (ES5) strictly prohibits the use of arguments.callee(). To avoid this, either name function expressions or opt for a function declaration that calls itself. [MDN] How can we refer to the o function within itself in this scenario? fun ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

Utilizing a variety of textures across various surfaces of a single geometry

I'm new to working with Three.js and I have a question about displaying multiple images over a plane geometry. Here is the scenario: Imagine a simplified case where we have a plane divided into tiles like this: +---+---+---+ | 1 | 2 | 3 | +---+- ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

Personalized AngularJS Filter that operates according to a boolean value

Trying my hand at creating a custom filter with a specific purpose determined by a dropdown menu selection. The filter should be able to display hidden items, non-hidden items, or all items. Check out the dropdown menu below: <select class="span1" ng- ...

Achieving error handling in PHP API using Phalcon framework

I am in the process of developing an API consumer service using AngularJS, while my API is built with the Phalcon micro framework. The issue I am encountering pertains to how errors are handled when the API responds. It appears that when there is an error ...

Tips on incorporating a high-quality animated gif for optimal user engagement

I'm looking for advice on how to optimize the loading of a large animated gif (1900px wide) on my website. Currently, the initial load time is quite lengthy and the animation appears choppy. Is there a more efficient method to load the gif without slo ...

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

Disable Autocomplete Chip functionality when only one can be selected

When multiple is set to true, I prefer the Chip option. Is there a way to enable the Chip functionality even when multiple is set to false? <Autocomplete className={classes.search} options={top100Films} ge ...

The challenge of incorporating Laravel, Vue, and JavaScript into a Blade template

It may seem like a silly question, but I am struggling to find a solution. My goal is to load a Vue component and JS file into a blade view. When I include the following: <script src="{{ asset('js/app.js') }}"></script> <script sr ...