How can I use Angular to remove the "selected" class from one li element and then add it to a different li element?

I am trying to achieve a specific functionality in the code below (click Demo link). How can I remove the "selected" class from the "Zero" li item and then add it to the "Two" li item? Essentially, what I want is to deselect the current li item and select a new one.

In the Demo code, it seems that the removeClass() function affects the newly selected li as well, resulting in none of the li elements having the "selected" class. If you comment out line 11 in the JavaScript code, both "Zero" and "Two" will have the "selected" class. However, the desired outcome is for only "Two" to have the "selected" class.

Any suggestions or recommendations on how to achieve this would be greatly appreciated.

Demo

Answer №1

Check out this revised version. It's important to reconsider your approach when working with an angular app. Your controller shouldn't handle jquery manipulation like it currently does. Take a look at my example and observe how the DOM state is determined by the scope data state. There's no need to manually track classes applied to elements or understand the template's inner workings.

Another technique for handling selection logic is to introduce a separate scope variable, $scope.selected. This allows you to eliminate the select() scope function and simply implement the following in your template:

<li ng-repeat="item in items"
    ng-class="{selected: item == selected}"
    ng=click="selected = item">
    {{item.text}}
</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

What steps should I take to adjust the alignment of the arrows that should be beside the links in my footer?

Previously, the text was aligned until I added links to them. Now they are not aligning properly. Any assistance would be highly appreciated. Below you can find my CSS and HTML code along with a screenshot of the specific issue. I am unsure about the root ...

Underlining.js - Evaluating differences between two arrays containing objects

Looking to cross-reference two arrays containing objects with different key names, utilizing underscore... array1 = [{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0829586..."], first_name:"asad"}, {email:"<a href= ...

Is there a way to optimize my code to ensure that the CSV export only occurs after all AJAX queries have been completed?

After clicking the button, the code below is triggered. Although the CSV is created, it turns out empty. The console.log(rows) displays the expected output but comes with a note saying Value below was evaluated just now. The main issue lies in how to make ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

Utilizing JQuery for parsing information

I am working on a project that involves displaying Google Maps API on one tab and images on another within a container. The goal is to have the image in the second tab change when a location is selected from the list. To achieve this, I have set up a hidd ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

Modify the flashVars in flowplayer using swfObject to switch videos

I am currently implementing a cross-browser solution to play .mp4 video files and I need to ensure compatibility with IE8 and newer versions. The approach I am using is referenced from Dev-Metal and so far, everything has been successfully configured and i ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Retrieve / - - - - ms within meanio

I have successfully set up the mean stack using the steps provided: $ curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash $ sudo apt-get update $ sudo apt-get install nodejs $ npm install -g gulp $ npm install -g bower $ sudo npm install -g mean- ...

How to reference an object from an external file in TypeScript using Ionic 2 and Angular 2

I am currently developing a mobile application with Ionic2 and have integrated a simple online payment service called Paystack for processing payments. The way it operates is by adding a js file to your webpage and then invoking a function. <script> ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

Is there DnD support in Chrome?

Looking to create a unique shopping cart similar to the one featured on netTutsPlus, but encountered compatibility issues with Chrome and Opera when implementing the drag and drop feature. In search of a solution that will work seamlessly across both brow ...

"Exploring three.js: How to locate the closest point on a Mesh to the position of

In this scenario, picture a three.js scene configured with an OrthographicCamera and OrbitControls: https://i.sstatic.net/rhJnr.png When the user moves the yellow disc (representing the Sun), it should follow along its corresponding yellow circle. To bet ...

Difficulty encountered when using `require('bignumber.js')` in Truffle test, despite successful installation as shown by `npm ls -g` (Windows)

While exploring solidity code testing with truffle, I encountered the need to work with BigNumber values returned from or sent to contracts and decided to include the appropriate library. My current test consists of just one line: let BigNumber = require(& ...

Utilizing asynchronous calls within a forEach loop for executing Firebase operations

My dilemma lies in the inability to successfully implement this code using Firestore (although I'm not entirely sure if this is relevant). The specific code snippet is as follows: prestamoItems() { var myarray = []; var myobject = {}; ...

Is there a way to position a slide container so that it is initially 10% from the left margin, and then shifts to be 10% from the right margin when it reaches the end? (Using vue-awesome

I'm facing a bit of challenge with this question, and I hope someone can help me find a solution. Currently, I am utilizing vue-awesome-swiper (). My goal is to achieve the following layout: An initial left margin of 10%: https://i.sstatic.net/AoLhK ...

What makes Safari for Windows stand out when it comes to AJAX?

What sets Safari for Windows apart when it comes to handling AJAX requests? Moreover, are there any potential issues or challenges I should be aware of? ...

When utilizing Simple Git in Node.js, conducting a Git diff on a specified file will result in the retrieval of the

I'm currently integrating the Simple Git library into my Node.js project to retrieve the diff of a particular file. However, I am facing an issue where using the git.diff(["--"], file) function returns the entire diff instead of just the diff for the ...

Disabling the movement of arrows in the client-testimonials-carousel plugin

This plugin that I'm currently using is working flawlessly: However, I'm unsure about how to make the arrows stationary and prevent them from moving. Currently, they are centering themselves based on the height of the div, but I want them to rem ...