"Utilizing AngularJS for advanced filtering and searching functions, along with

After exploring various solutions on Stack Overflow to identify unique values in angular.js (I am still learning), I am faced with a challenge. My goal is to present these unique values within a select form and use them as filters for data displayed in a table.

In essence, I have a dataset that I want to showcase in a table. Within the table header, I aim to include a select dropdown containing unique values from a specific column in the data. This select dropdown should allow users to filter the displayed table based on their selections.

I have been attempting to implement the following code:

app.filter('unique', function () {
return function (collection, keyname) {
var output = [],
    keys = []
    found = [];

if (!keyname) {

    angular.forEach(collection, function (row) {
        var is_found = false;
        angular.forEach(found, function (foundRow) {

            if (foundRow == row) {
                is_found = true;                            
            }
        });

        if (is_found) { return; }
        found.push(row);
        output.push(row);

    });
}
else {

    angular.forEach(collection, function (row) {
        var item = row[keyname];
        if (item === null || item === undefined) return;
        if (keys.indexOf(item) === -1) {
            keys.push(item);
            output.push(row);
        }
    });
}

return output;
};
});

Here is an example of my HTML structure:

    <th> Number:        
    <br/>
     <select ng-model="search.number"  
             ng-options="row.number for row in data | unique:'number'">
    <option value=""> </option>
    </select>
    </th>

The table data itself is represented like this:

        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="r in data | filter:{ number: search.number,  }">
        <td> {{r.number}}</td>
        </tr>
        </tbody>
        </table>

Although the output works, the value does not set correctly leading to no matching rows when filtering (as 0,1,2,3.. do not correspond to any data rows).

<select ng-model="search.number" 
ng-options="row.numberfor row in data | unique:'number'"  
class="ng-pristine ng-valid">
<option value="" class=""> </option>
<option value="0">1023 456789</option>
<option value="1">1024 456789</option>
<option value="2">1025 456789</option>
<option value="3">1023 111999</option>
<option value="4">1024 111999</option>
</select>

Furthermore, I have explored an alternative unique function:

/*          
app.filter('unique', function() {
return function(input, key) {
    var unique = {};
    var uniqueList = [];
    for(var i = 0; i < input.length; i++){
        if(typeof unique[input[i][key]] == "undefined"){
            unique[input[i][key]] = "";
            uniqueList.push(input[i][key]);
        }
    }
    return uniqueList;
};
}); */

Unfortunately, modifying [key] in this line uniqueList.push(input[i][key]); was required to display values in the dropdown, but controlling the options' values remains an issue.

No errors are reported in the console.

While I have 10 columns/fields available for filtering, I have only demonstrated one here.

If anyone could provide guidance or suggestions, it would be greatly appreciated. Thank you.

Edit:

I came across a directive that might be helpful, although handling similar key-value pairs presents challenges. Is there a simpler approach?

app.directive('mySelect', [function () {
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    template: '<select ng-options="key as value for (key, value) in myMap" ng-transclude></select>',
    link: function postLink(scope, element) {
      scope.myMap = {"1":"1","2":"2","3":"3"}; 
   // e.g. hashmap from server
    }
};

Answer №1

This method turned out to be effective.

<select ng-model="search.<?php echo $column; ?>" 
        ng-options="v for (k, v) in data 
                | orderBy:'<?php echo $column;?>' 
                | unique:'<?php echo $column;?>' ">
        <option value="">select</option>
</select>

I am currently stuck within a loop that is examining each column in a CSV file.

For example, I am aiming for full Excel-style filtering with any CSV file provided.

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

How can I assign a default value for a multiple select dropdown list in AngularJS?

I am currently facing an issue with my multiselect dropdown. The code for the dropdown is as follows: <select id="year" multiple ng-model="type" ng-disabled="!type1" > <option value="all" selected>all</option>; <option value= ...

The loading of script files is not working properly in an AngularJS web API application

After developing an application in angularjs that utilizes angular routing for calling web api services, everything functions properly when run from visual studio. However, upon deploying the application on an IIS web server, the script files fail to load ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

Keep an ear out for socket.io within an Angular application

I am trying to connect socket.io with my angular application. I have come across some examples of creating a service that can be accessed by the controller, and I understand that part. However, I am looking for a solution where all controllers can respond ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

Passing an object from an Angular application to a backend server in Node.js using the

I have a YAML file with the following structure: Layouts: - Name: Default Layout LayoutId : 1 ConfiguredSegments: LiveA : Height : 100 Id : LiveA Ref1A : ...

Is there a way for me to record the input field's value to the console every time it is altered?

Currently, I am diving into the angularjs phonecat tutorial (specifically step 5) in an effort to grasp a deeper understanding of how angular operates. However, I have been struggling to successfully log the input field value to the console. Despite trying ...

Clicking on text within a DIV using jQuery

How can I use jQuery to show an "alert" when text inside a DIV is clicked, excluding images and other tags? The texts are contained within various DIVs along with images and tags. Is there a way to achieve this using jQuery? Check out the jsFiddle example ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Monitoring a variable inside a service using AngularJS

I am currently in the process of developing a web application using AngularJS. My application consists of a primary view (Index), a child view (Dashboard), and a grandchild view (Raiding The Rails). http://localhost:4000/#/dashboard/raiding-the-rails/1 ...

Two commands, a set of matching controllers, and an identical templateUrl

As a beginner in AngularJS, I am facing a challenge where I need to use one template for two directives. The issue is that the behavior of the first directive overrides the second one, even though I have specified different controllers for each. This seems ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Modifying the background color of a div with ng-click functionality

Having trouble changing the background color of a div that is already styled with white for odd elements and grey for even elements. I'm not sure why it's not working in Jsfiddle. The div also has an ng-click attribute that I haven't include ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Display error page when unable to load ng-view template

Is there a way to display a standard error page or template if a certain template cannot be loaded using ngRoute in Angular? I've come across suggestions that subscribing to the $routeChangeError event might help, but I'm not sure what steps to ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Warning message about unhandled promise rejection in Protractor async/await causes UnhandledPromiseRejectionWarning

Currently in the process of updating my protractor tests to use async/await (Link). The migration has been going smoothly until I encountered a recurring issue. Here are the steps of my test along with an example code snippet illustrating the problem: G ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Secure Angular Rails application complete with authentication features and token authentication

I am currently developing a basic app using AngularJS for the frontend and Rails for the backend. Previously, working solely with Rails made it easy to use the Devise gem and work with Rails views (erb). However, I now find myself in a completely different ...

Is it possible to expand the capabilities of the filterFilter function in AngularJS without making

I have made changes to the AngularJS filterFilter function to allow for exact matches. This means that when searching for '1', only '1' will be returned, not '11', '12', and so on. function filterFilter() { return ...