Maintain the selected list item after filtering in AngularJS

I am facing an issue with highlighting selected items in a list. I have three first names: Roy, Sam, David displayed in a ul as list items. Initially, I can toggle each li on click just fine. However, after performing a search and returning to the list, the selected items are no longer highlighted. Can anyone suggest a solution to keep the selected items highlighted even after a search? Here is the code snippet:

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

app.controller("con",function($scope){
$scope.firstNames = ['Sam', 'David', 'Roy'];

});

app.directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.toggleClass(attrs.toggleClass);
            });
        }
    };
});
.active {
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<input type="text" ng-model="searchText"/>
<ul ng-repeat="firstName in firstNames | filter:searchText">
<li toggle-class="active">{{firstName}}</li>

</ul>
  
</body>

http://jsfiddle.net/baa2G/126/

Any help will be appreciated!

Answer №1

Consider using the ng-class directive instead. It's important to prioritize your data model when designing the view.

<li ng-class="{active: selected[firstName]}" 
    ng-click="toggleSelected(firstName)">{{firstName}}</li>

Controller:

   $scope.selected = selected = {};
   $scope.toggleSelected = function(name){  
      selected[name] = !selected[name];
   }

Check out this Demo for more information

Answer №2

Oops! I made some changes because I misunderstood your question.

Utilize Angular to save your choices in the controller.

I have updated your firstNames to users and converted each entry into an object.

$scope.users = [
    {name: 'Sam', isSelected, false},
    {name: 'David', isSelected, false}, 
    {name: 'Roy', isSelected, false}
];
$scope.toggleSelection(user){
    user.isSelected = !user.isSelected;
}
<ul ng-repeat="user in users | filter:searchText">
<li ng-click="toggleSelection(user)" ng-class="{'active': user. isSelected}">{{user.name}}</li>

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

Adjustable value range slider in HTML5 with ng-repeat directive in AngularJs

I am facing a problem with my HTML5 range slider. After setting a value (status) and sending it to the database, when I reload the page the slider's value is always set to '50'. The slider is being generated within an ng-repeat from AngularJ ...

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

Is jQuery each function always sorting the elements?

In my JavaScript code, I have a specific object: var list = {134 : "A",140 : "B",131 : "C"} To iterate over the object, I use this code snippet: jQuery.each(list, function(key, value) { console.log(key + " - " + value); }); The expected output should ...

Error message displayed in jQuery dialog box

My dilemma arises when attempting to continuously call a dialog box for displaying and submitting an enquiry form on my website. Upon the first submission, everything seamlessly goes through. However, clicking the GO button (as shown in the HTML below) tri ...

PHP code isn't showing any posts

Context: I have implemented a PHP loop to generate a dynamic feed of my portfolio posts on my WordPress website. Issue: The first five posts are being displayed correctly, but the subsequent posts are not. I'm uncertain about the underlying cause and ...

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

jQuery is malfunctioning following an AJAX request

Can anyone help me fix an issue with my jQuery code? I have a hidden div that should be shown when the mouse hovers over a sibling element. However, it seems like after my AJAX function is executed, the jQuery stops working. <div class="parent"> ...

Ways to identify when the user has stored a file on their local disk using Angular/NodeJS

In my NodeJS backend, I am generating a JSON file temporarily to store the information provided by the user in a form. Upon clicking the download button at the end of the form, I execute a Python script within NodeJS to verify the data and create a tempora ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...

How can I identify when a form has been edited in order to update the database with those changes only?

Currently, I have a form with over 50 fields. While I've successfully implemented functionality for inserting, selecting, and deleting records, I'm struggling with updating a record. Specifically, if a user only updates one or two fields out of t ...

Incorporate a corner box feature to bring attention to the typed.js functionality

I have successfully integrated typed.js into my project and now I am looking to replicate the highlighted text with an excel-like box in one corner. I've managed to get the text typing out while also adding an SVG for the box in HTML, but I'm hav ...

Is it required to double click checkboxes to uncheck them?

My checkboxes require 2 clicks to be unchecked, even though one click is enough to check them. This issue occurs in all 7 checkboxes and there is no onchange() function or similar in TS. import { Component, OnInit, Inject } from '@angular/core&apos ...

The validation in AngularJS does not disappear while typing in the text field

After reading through this particular question, I decided to experiment with a way to hide validation messages when typing in a text field. Here's the code snippet I tried: $scope.click = function () { showVal(); } function showVal( ...

What is the best way to update the switchery checkbox after it has already been initialized?

I have set up the switchery using the code snippet below. var ss_is_schedule_edit = document.querySelector('.ss_is_schedule_edit'); var mySwitch = new Switchery(ss_is_schedule_edit, { color: '#8360c3' }); However, I am unable to toggle ...

Is it considered fashionable to utilize HTML5 data attributes in conjunction with JavaScript?

Currently, I am utilizing HTML5 data attributes to save information such as the targeted DOM element and to initialize events using jQuery's delegation method. An example of this would be: <a href="#" data-target="#target" data-action="/update"> ...

Verifying the status of a checkbox label in Java using Selenium

I am currently working on an automation project using Selenium and I'm struggling to figure out how to check the status of a checkbox input. Has anyone else encountered this issue before? Here is a sample code snippet in JavaScript with jQuery: $("i ...

AJAX jQuery requests can flatten arrays when they are sent

The below code shows an endpoint written in Express, using the body-parser middleware. app.post("/api/poll/new",api.NewPoll); api.NewPoll = function(req,res){ if(!req.body) return res.status(400).send("MISSING BODY"); console.log(req.body,typeof(r ...

What is the best way to retrieve the value of a dynamically created button in code?

I am dealing with a situation where I have a button that is supposed to fetch some data based on the classroom ID. button(type='button' id='getButton', onclick='get()', value=classroom.id ) Class Students Additionally, I ha ...