Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the implementation of Bootstrap's 'labels' classes. Everything seems to work fine up until this point... However, there is one problem that I encounter when clicking on the 'Try again' button - I am unable to revert the colors back to their initial state because I cannot set the value of 'this.selected' to 'false'. Please refer to the code snippet below for clarification.

Although I acknowledge that this problem may not be too complicated, I find myself stuck and would greatly appreciate any guidance or hints from anyone who can assist me.

<h2 class="jumbleW inline" ng-repeat="w in word track by $index">
  <span ng-class="{'label': true, 'label-primary': !this.selected, 'label-warning': this.selected}" ng-click="pickWord(w)">{{w}}</span>
</h2>

<button class="btn btn-danger btn-xs" ng-click="clear()">Try again</button>

EDIT : Please excuse any beginner mistakes that I may have made. For clarity purposes, let's consider the revised version of the provided code (which consists only of HTML). Additionally, here is my pickWord() function:

$scope.pickWord = function(w){
    this.selected = !this.selected;
    if (this.selected == false) {
        $scope.playerAnswer = $scope.playerAnswer.replace(w, "");
    } else {
        $scope.playerAnswer += w;
    }
}

Answer №1

Instead of using this, it is recommended to add a property to the ng-repeat object called w. If the value of w is an object, create an array for the selected index as shown below.

HTML:

    <h2 class="jumbleW inline" ng-repeat="w in word track by $index">
      <span ng-class="{'label': true, 'label-primary': selectedItems.indexOf($index) === -1, 'label-warning': selectedItems.indexOf($index) !== -1}" ng-click="pickWord(w, $index)">{{w}}</span>
    </h2>

<button class="btn btn-danger btn-xs" ng-click="clear()">Try again</button>

JavaScript:

$scope.pickWord = function(w, i){
    if(!$scope.selectedItems){
       $scope.selectedItems = [];
    }

    var index = $scope.selectedItems.indexOf(i);

    if(index === -1) {   // not selected already and add
       $scope.selectedItems.push(i);
        $scope.playerAnswer += w;
    } else {   // selected already and remove
       $scope.selectedItems.splice(index, 1);
       $scope.playerAnswer = $scope.playerAnswer.replace(w, "");
    }
}

$scope.clear = function(){
   $scope.selectedItems = [];
};

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

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Tips for utilizing a single mongoose default connection across various files in MongoDB?

I'm struggling to figure out how to share a mongoose connection across multiple files. Here's an example: User.js var mongoose = require("../DataAccess/DbConnection"); var userSchema = new Schema({ email: {type: String, required: true,max ...

A tutorial on utilizing a bundle in webpack based on certain conditions

My project consists of an app.bundle.js (the main app bundle) and two cordova bundles: iosCordova.bundle.js and androidCordova.bundle.js. Depending on whether the user is logging in on an iOS or Android device, I only script src one of them. All the bundle ...

Utilizing null values within the map function in React JS

I am currently developing an application using React JS. The app displays a list of users along with the status of books (available, taken, or requested) for each user. However, I'm encountering an issue where even after filtering out the books based ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

WebStorm 6 does not recognize the post method in Node.js Express

I recently started learning about node.js and decided to experiment with the express module in my application. Everything was going well until I attempted to use the app.post method. I am developing my app on WebStorm 6.0.2 and it doesn't seem to reco ...

A guide on successfully handling errors while utilizing S3.getsignedurlpromise() in node.js

I am faced with a challenge in my project involving a node.js server that downloads images from an s3 bucket and serves them to a React client. The issue arises when the wrong file key is sent to the S3 client, as I want to handle this error gracefully by ...

"Exploring the seamless integration of easyXDM, AJAX, and En

In this new inquiry, I am facing a similar challenge as my previous query regarding loading a PHP file into a cross-domain page with dynamic element height. However, I am now exploring a different approach. Although I have managed to load my script into a ...

What is the best way to replicate the Ctrl+A action on an element using jQuery or JavaScript?

Is there a way to trigger the Ctrl+A key combination in a textarea element when a specific event occurs, without resorting to caret positioning or selecting all text separately? I'm looking for a method that simulates hitting Ctrl+A using a cross-brow ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

What is the best way to create a backup copy of my project using git?

To ensure the safety of my project, I took the necessary steps to back it up. First, I initialized a repository using git init Following that, I committed all files by executing git add . git commit -am "first commit" Now, the next step involves pushin ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Tips for implementing HTML5 validation followed by automatic redirection to a different page

I'm new to web development and struggling with how to make a button both validate inputs and redirect to another page. Using the onclick = "" function, I can validate inputs like emails and telephone numbers, but I'm having trouble making it so t ...

Image Switching Hover Bug

HTML: <div id="logo"></div> <div id="coming-soon"></div> JavaScript: $(document).ready(function(){ $("#logo").hover( function(){ $("#logo").fadeTo(300, 0); $("#coming-soon").fadeTo(300, 1.0 ...

What did I overlook in my AJAX implementation?

When a user selects a value from the dropdown menu, an Ajax call must be made to the server to retrieve some values in JSON format. Below is the Ajax code //AJAX Security $('#ddlSecurityLevel').change(function () { if ($('#ddlSecurityL ...

Leverage the Redux store as the source of data for sending a POST request

For my React project, I designed an input interface and saved the data in a Redux state. Afterward, I set up a new action for making an API call to post the data. When using a constant value as the "data" parameter, everything functions properly. However ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...