Angular ng-repeat with toggle filter

Looking for a way to display data in an angular application using ng-repeat? Want to add and remove filters on the displayed data with a simple click? You're in luck. Implementing a toggle filter functionality is easier than you think.

If you've already started, your view might look something like this:

<ion-item class="row" ng-repeat="t in tickets">
    <div class="col" ng-click="toggleFilter(t.name)">{{t.name}}</div>
</ion-item>

And your controller code could be similar to this:

.controller('TicketCtrl', function ($scope, $filter) {
    $scope.toggleFilter = function (name) {
        name = $filter('getSlice')(name);
        alert(name);
    }
});   

While the alert displays the correct filtered item, the view doesn't update accordingly. This issue might stem from the child scope of ng-repeat. But fear not, there's always a solution waiting to be discovered. Any suggestions or solutions?

Answer №1

To effectively monitor the status of each row (whether clicked or not), it is recommended that you maintain a record of it. It is advisable to retain the existing name of the scope property for consistency.

Below is the code snippet that will accomplish this task:

<ion-item class="row" ng-repeat="t in tickets" ng-click="t.clicked=!t.clicked">
    <div class="col" ng-if="t.clicked">{{t.name | getSlice}}</div>
    <div class="col" ng-if="!t.clicked">{{t.name}}</div>
</ion-item>

Answer №2

The issue you are encountering is due to not updating the view properly in your AngularJS code. In $scope.toggleFilter, you are modifying a local variable instead of the variable bound to the view. To reflect changes in the view, you need to modify the bound variable directly. You can achieve this by using the $index iterator variable provided by ngRepeat. https://docs.angularjs.org/api/ng/directive/ngRepeat

Here is an example of how you should handle it:

-view:

<ion-item class="row" ng-repeat="t in tickets">
    <div class="col" ng-click="toggleFilter(t.name, $index)">{{t.name}}</div>
</ion-item>

-controller:

.controller('TicketCtrl', function ($scope, $filter) {
    $scope.toggleFilter = function (name, index) {
        $scope.tickets[index].name = $filter('getSlice')(name);
        alert(name);
    }   

PS Off topic: If you are using Ionic framework for mobile devices and utilizing ng-repeat, consider using the collection repeat directive for better performance. Mobile devices may experience smoother scrolling with collection repeat compared to ng-repeat due to Angular's two-way binding mechanism. http://ionicframework.com/docs/api/directive/collectionRepeat/

Answer №3

To keep things straightforward, it's best to create a wrapper around the code:

Here is the HTML structure:

<div ng-app="app">
    <div ng-controller="ctrl">
        <button ng-click="toggleFilter()">Toggle Filter</button><br/>
        <span ng-repeat="item in data | filter:myFilter">
            {{item}}<br/>
        </span>
    </div>
</div>

And here is the JavaScript logic:

angular.module('app',[]).
controller('ctrl', function($scope){
    $scope.data = [1,2,3,4,5,6,7,8,9,10];
    $scope.shouldRunFilter = false;

    $scope.myFilter = function(item){
        if($scope.shouldRunFilter)
        {
            return item > 5;
        }

        return item;
    }

    $scope.toggleFilter = function(){
        $scope.shouldRunFilter = !$scope.shouldRunFilter;
    }
});

You can view the functioning example on JSFIDDLE.

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

utilizing angular syntax within a web application developed on the Django framework

Recently, I delved into the world of Django while also having experience in AngularJS. I found myself perplexed by Django's static media rendering, which utilizes the same moustache syntax as Angular. So, how can I effectively use Angular expressions ...

Set up npm and package at the main directory of a web application

Currently, I am in the process of developing a web application using node.js. Within my project structure, I have segregated the front-end code into a 'client' folder and all back-end logic into a 'server' folder. My question revolves a ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...

What is the method to convert Javascript values from pixels to percentages?

Is it possible to change the scrolltop value dynamically based on a percentage of the user's screen size? I've been trying to achieve this using JS but haven't had any luck. Here is a link to a codepen that showcases the issue: [link] (http ...

Display a specific template in the detail grid of the Kendo Grid depending on certain conditions

I've been using the Kendo Grid and it's been working well for me. I have a requirement to check each row in my grid to see if it contains a specific value, and based on that, bind data using different templates. Is this feasible? Below is the cod ...

What is the best way to switch from http to https in a React application?

When performing audits in Chrome, I encountered a net::ERR_EMPTY_RESPONSE error because Lighthouse was not able to consistently load the requested page. Google developers have recommended configuring my server (possibly node.js) to redirect from http to ht ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

Tips for altering the color of a specific bar in the Material UI BarChart component

I have implemented the following code to generate a Graph: const namesArray = Object.values(tableData).map(item => item.name); const valuesArray = Object.values(tableData).map(item => item.value); return ( <Box> <SimpleCard ti ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

Exploring the inner workings of AngularJS SEO in HTML5 mode: Seeking a deeper understanding of this hidden functionality

There are plenty of resources available for incorporating SEO-friendly AngularJS applications, but despite going through them multiple times, I still have some confusion, especially regarding the difference between hashbang and HTML5 mode: In hashbang (# ...

Pug Template Not Displaying Emojis or Special Characters in Sendgrid Email Subject Line

There seems to be an issue with rendering emojis or special characters in the subject header of the pug file, although they work perfectly in the body. I have compiled both the body and subject header separately using pug. const compileHtmlFunction = pug.c ...

Endless scrolling dilemma

I came across an example of infinite scrolling and attempted to implement it myself. Despite correcting all the errors I could find, it still refuses to work. Below is the directive code: module.exports = /*@ngInject*/ function scrollDirective($rootScope ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

Create buttons to increase or decrease values using Bootstrap and JavaScript

What is the proper way to make this button function properly? I tested adding this line of javascript code, however it prompts an alert without clicking on the buttons as well. document.querySelector(".btnminus").addEventListener(onclick,ale ...

Display the contents of a <div> tag from one HTML file onto another HTML file

Recently I embarked on learning HTML and came across a peculiar doubt. My goal is to create a section div on the first page that changes dynamically based on the menu item clicked, rather than redirecting to another HTML page. I've experimented with s ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

Exploring nested documents in mongoDB with mongoose

As a novice full stack web developer, my current project involves creating a movie rating website. To achieve this, I have set up a user schema using mongoose with a ratings subdocument. Here is an example of the schema: const ratingSchema = new mongoose. ...

Struggling with an error while experimenting with tensorflow/teachable machine on vuejs

After experimenting with vuejs and , I encountered an issue while trying to export the model for my project. As I adjusted the syntax to fit Vue, I hit a roadblock when the code returned an error stating "cannot read properties of undefined...." console.lo ...