Preserve the array's status following a personalized filter in AngularJS

I am currently working with two arrays of data displayed in a tree structure and have established a relationship between them.

$scope.types=['odd','prime','square','even'];
$scope.items=['1','4','3','8'];

div ng-repeat="item in items| customFilter">item

Additionally,

div ng-repeat="type in types| customFilter">type

Both arrays are shown using ng-repeat, where selecting an item from one array affects the display of the other. For example, if '1' is selected, the state would change to:

$scope.type=['odd','prime','square','even']; $scope.items=['1','4','3','8'];

The elements from the items array related to the type are then moved to the top.

Similarly, if 'even' is selected, the state would be:

$scope.type=['square','even','odd','prime']; $scope.items=['4','8','1','3'];

The bolded elements are highlighted on the page. I have implemented a custom filter in the ng-repeat to display and sort based on the relationship.

My challenge is that after sorting, the same state is not stored in the original arrays. Consequently, when I select an element from $scope.items, $scope.types reverts to its original state, causing the list on the page to readjust abruptly.

Answer №1

To keep track of changes in collections, you can use ng-change or $watch and utilize the $filter service in the controller to retrieve filtered values and save them to the same array.

For a demonstration, check out this sample: http://plnkr.co/edit/eW48QL2j30ZAKnwGzs3g?p=preview

<body ng-controller="MainCtrl">
    <select ng-model='opt1' ng-options='option for option in options1' ng-change='filter(options2, opt1)'></select>
    <select ng-model='opt2' ng-options='option for option in options2 | filter:opt1'></select>
    <button ng-click='clear()'>Clear</button>
  </body>

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

app.controller('MainCtrl', function($scope, $filter) {
  $scope.options1 = ['A','C','J'];
  $scope.options2 = ['Andrew','Chris Martin', 'Jeeva'];
  $scope.filter = function(collection, value){
    $scope.newoptions2 = $filter('filter')(collection, value);
    console.log($scope.newoptions2);
    $scope.options2 = $scope.newoptions2;
    $scope.options1 = [value];
  };
  $scope.clear = function(){
    $scope.options1 = ['A','C','J'];
    $scope.options2 = ['Andrew','Chris Martin', 'Jeeva'];
  }
});

Swap out 'filter' with your own 'customFilter'. Feel free to reach out if you need further assistance.

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

Creating a nested set of directives by iterating over an array within an AngularJS directive

When working inside an angularJS directive, I am attempting to iterate through an array and create a nested list of directives based on the values. The current version of the directive is as follows: Type Directive .directive("type", function($compil ...

When attempting to execute a Spring Boot CLI using the command "spring run app.groovy", an error is displayed stating "bash: spring: command not found"

When running the following command in git bash: $ spring run app.groovy An error is encountered, bash: spring: command not found The content of app.groovy includes: @Controller class JsApp { } ...

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

Tips on storing chosen language in local storage or cookies using AngularJS

As a newcomer to angularjs, I am facing the challenge of saving the selected language from a dropdown menu in HTML to either local storage or cookies. This way, when a user navigates to another page, the language they previously chose will be loaded and us ...

ensure that html tags display properly when retrieved from json in an angular directive template

Trying to embed ruby tags in a directive template but struggling with escaping them. Despite reading about $sce and filters, the confusion deepens as browser tabs multiply. The directive code is as follows: angular.module("ngFlashCard", ["ngSanitize"]).d ...

Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab ...

Sending a date to WebAPI from an HTML5 input field with type "date" using Angular - Tips and Tricks

Utilizing the HTML 5 Input type = "Date" control to interact with a .NET web API through Angular has presented an issue for me. While the date displays correctly formatted as "dd/mm/yyyy" on the HTML Control, I am encountering a formatting problem when re ...

What is the method to assign multiple values to ng-disabled in AngularJS?

Is there a way to assign multiple values for ng-disabled in AngularJS? The issue I'm facing is demonstrated in the following JS Fiddle: http://jsfiddle.net/FJf4v/10/ <div ng-app> <div ng-controller="myCnt"> <h3>A ->> ...

Only allow numbers to be entered into input fields using AngularJS

Currently, I am attempting to validate input as numbers in the fields below: Postal Code: <input type="text" id="zipCode1" name="zipCode1" size="4" maxlength="5" ng-model="zipCode1" ng-change="myNumbers(zipCode1)" /> <input type="text" id="zipCod ...

Implementing file uploads in an Ionic application with a Web API

My dilemma is as follows: I am working with a WEB API where I need to upload images of boards. What do I need to do? Allow the user to select an image from their phone Enable the user to add a name for the board When the user clicks submit, the entered ...

Understanding how to interpret language settings in AngularJS MVC 4

We currently have an application that is live in production. We are now adding a localization feature for English and Chinese languages only. Users will have the ability to switch between these two languages. I made changes to my route as follows: ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

Angular organizes the GET response in alphabetic order

Currently, I am working on developing an interactive table in Angular that displays information from a SQL database. The technology stack I have chosen to work with includes MSSQL, Express.js, and AngularJS. While logging the response in Node, I noticed t ...

Creating a feature in Angular JS that allows for each item in a list to be toggled individually

Looking for a more efficient way to toggle individual buttons without updating all at once? Check out this basic example where each button toggles independently by using ng-click="selected = !selected". Instead of updating all buttons at once, you can achi ...

Single-line form with labels positioned above the input fields

For my web app project, I am using AngularJS and Bootstrap 3 for CSS (although my CSS knowledge is limited). I am trying to design an inline form with 5 input fields and labels positioned on top of them. The first field should take up more space than the o ...

Tips for modifying the value and refreshing the array

I retrieve data from $scope.roleinfo = {"QA":[{"White Box Testing":0},{"Black Box Testing":0}],"Development":[{"Server Side":0},{"UI":0},{"Back end":0}]}; Then, I present these values in a table. Now, I need to update the maxcount and create an array w ...

Is there a way to set table column headers in ngGrid using values from another array?

The JSON I am working with is organized into 'headers' and 'rows'. For example: { "headers": ["id","timestamp from","blah1","blah2"], "rows": [["69517737","1416932540011285849","104220.00","170968251000.000: ...