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

Is adding ng-click in a template counterproductive to the concept of MV* architecture?

When working with AngularJS, you may come across instances where the ng-click handler is directly connected to an HTML element like <a> or <button>. Take for example the snippet below (borrowed from an Angular homepage sample), where the click ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

The logo positioned on the left with menu links perfectly centered

Looking for Help with Navigation Layout Greetings. I am encountering some challenges while trying to code the navigation layout depicted in the image (linked above). My goal is to have the logo, which is an image, aligned on the left side and the menu lin ...

Execute javascript function upon user scrolling to a designated section in the webpage

Is there a method to trigger a unique function every time a user scrolls to a different div or section of the page? ...

Angular/JS encountered a premature end of program unexpectedly

I am taking my first steps in the world of web development with Angular (and JavaScript in general). I have been trying to rewrite some basic and common examples using Angular. One thing I attempted was to display a simple message using data binding. This ...

What could be causing the .remove() method to malfunction in my current environment?

I'm new to jQuery and struggling with the .remove() method. Despite finding similar questions, I'm still unable to solve my issue. Within an HTML file, there's a form alongside a div acting as an alert box, indicating whether the form was v ...

Using jQuery to transfer array values to a different group of elements

Looking for help with this code snippet: jQuery(document).ready(function($) { var i = 0; var values = []; var element = $('.source'); element.each(function(i) { values[i++] = $(this).text(); }); }); I'm tryi ...

Using an anonymous function in Javascript to change the background color of a div on mouse-over directly from the HTML code

I came across this code snippet in the provided link and as a beginner in JavaScript, I am unsure how to call the JavaScript function from the HTML code. Due to them being anonymous functions, I am struggling to invoke them. Can someone guide me on how to ...

What is the best way to conceal a portion of a child element that exceeds the size of its parent container?

My <div> contains a <p>, but sometimes the text in the <p> exceeds the boundaries of the div. <div style="width: 100px'; height='100px';"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit ...

Exploring AngularJS: Utilizing limitTo and filter

I'm having some trouble with using angular's limitTo and filter together. I want to search for a value in the search box, then apply a limit to the number of results displayed by entering a number in the filter box and clicking apply filter. Howe ...

Bootstrap's versatile footer positioning adaptation

I am working with a simple layout design: +----------+ | Header | +----------+ | | | Content | | | +----------+ | Footer | +----------+ My goal is to ensure that the footer is positioned: at the bottom of the viewport when there ...

Is it possible to not return anything in a jQuery ajax call?

When I make an ajax call, I am using the following code: $.ajax({ url: $.grails.createLink('class', 'action'), data: {id: id1}, async: false }); This triggers a Grails method to be called: def action = { } In my expe ...

Confusion around Angular's $animate feature

I am struggling with understanding AngularJS $animate. I cannot figure out if my mistake is minor or a major misconception. Despite trying to simplify the code, it remains quite lengthy. Nonetheless, it should work without any issues. <!doctype htm ...

How can you determine whether the CSS of a <div> is defined in a class or an id using JavaScript/jQuery?

Hey there, I'm currently working on dynamically changing the CSS of a website. Let's say we have a div like this: <div id="fooid" class="fooclass" ></div> The div has a class "fooclass" and an ID "fooid", and we're getting its ...

Could the problem with inset box-shadow and large border-radius on one side be related to Chrome?

Have you noticed a discrepancy in the inset box-shadow behavior with large border-radius on one side, particularly in Chrome? I'm curious about which browser is showing accurate results. Here's how it appears in Chrome: https://i.stack.imgur. ...

Ruby on Rails slider bar functionality

Currently, I am developing a video-focused application using Ruby 1.9.2 and Rails 3.1. One of the key features I need to implement is a slider bar that allows users to adjust the total duration of a video in real-time. Despite my attempts to use HTML5 fo ...

Achieving Perfect Alignment in Dreamweaver: Crafting a Stylish Header Container

Hello, I am currently working on a Dreamweaver site and have created a CSS style sheet within my template that includes a div tag called #HeaderBox. My goal is to make this box 40% of the screen's size, with specific pixel dimensions if necessary. I a ...

Can you provide instructions on connecting a navigation bar button to a sidebar that appears when clicked?

On my webpage, I have three buttons at the top. One of them, the Contact Me button, is supposed to reveal a hidden sidebar on the left side when clicked. However, I am having trouble getting the sidebar to appear when clicking Contact Me. An example of wh ...

What is the best way to implement a toggle button in Angular that alternates between saving and unsaving content with two separate

I'm in the process of developing a toggle save/unsave feature similar to what is commonly seen on Reddit pages. Intended Functionality A list of objects (stories) are displayed, each with a link labeled "save" if not already saved, and "unsave" if a ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...