Upon loading the page, include a class to a specific element within an AngularJS ng-repeat function by evaluating the content of a JSON object

I have a group of buttons that are generated from a json object. Whenever a user clicks on a button, it changes color (referred to as the selected color) using the ng-class directive with bootstrap classes. If the same button is clicked again, it reverts back to its default color.

What I am trying to achieve is to set the selected color for each button on page load where the item's SelectedId matches the specific item's Home/AwayTeamId. In other words, if a user has made selections previously, the SelectedId will be a non-zero number that corresponds to either the HomeTeamId or AwayTeamId, and the selected button should display the selected color.

I have attempted to implement this logic in the code below, but unfortunately, the buttons are not toggling at all. I would appreciate it if someone could review my code and provide some guidance. Thank you.

HTML:

<div class="form-horizontal" data-ng-repeat="item in event.Events">
    <div class="form-group">
        <div class="col-xs-12 col-md-6 col-lg-6">
            <button type="button" class="btn form-control"
                    data-ng-class="[pickChosen == 1 || checkIfChosen(item.SelectedId, item.homeTeamId, 1) ? 'btn-success' : 'btn-default']"
                    data-ng-disabled="item.Locked === 1"
                    data-ng-click="buttonToggle($index, 1)">
                <span class="hidden">{{item.homeTeamId}}</span>
            </button>
        </div>
        <div class="col-xs-12 col-md-6 col-lg-6">
            <button type="button" class="btn form-control"
                    data-ng-class="[pickChosen == 2 || checkIfChosen(item.SelectedId, item.awayTeamId, 2) ? 'btn-success' : 'btn-default']"
                    data-ng-disabled="item.Locked === 1"
                    data-ng-click="buttonToggle($index, 2)">
                <span class="hidden">{{item.awayTeamId}}</span>
            </button>
        </div>
    </div>
</div>

Angular:

app.controller('dashController', function ($scope) {
    $scope.buttonToggle = function (index, buttonNumber) {
        if (buttonNumber === this.pickChosen) {
            this.pickChosen = 0;
            picks.splice(index, 1);
        } else {
            this.pickChosen = buttonNumber;
        }
    };
    $scope.checkIfChosen = function(selId, teamId, buttonNumber) {
        if (selId === teamId) {
            this.pickChosen = buttonNumber;
        } else {
            this.pickChosen = 0;
        }
    };
});

Example json object:

[{"EventId":xxxxxxxx,
 "HomeTeamId":832,
 "AwayTeamId":575,
 "Locked":1,
 "SelectedId":0
},
{...},
{...}]

Answer №1

Don't forget to include a return statement in your checkIfChosen() function. For example,

pickChosen == 2 || checkIfChosen(item.SelectedId, item.awayTeamId, 2) ? ....
.

Additionally, keep in mind that the use of this in controller methods always refers to the controller instance, regardless of which button triggers the method.

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

Where do I find the resultant value following the completion of a video production through editly?

Hey there, I have a quick question... I was following the instructions in the README for editly, and I successfully created videos by calling editly like this: // creating video editly(editSpec) .catch(console.error); The only issue is that I am using Ex ...

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

Every time I try to run npm start on my React app, I keep receiving the error message "? Something is already running on port 3000"

Whenever I try to start my React server, I keep receiving the message "? Something is already running on port 3000" in my terminal. Strangely, there is nothing actually running on port 3000. Here are the steps I have taken to try and solve this issue: Re ...

Can anyone tell me what js stands for?

I stumbled upon this snippet of code and am curious about what it does. Is it some sort of array? test = {a: [1,0,0], b:[0,1,0], c:[0,0,1]}; If I wanted to access the array for A specifically, how would I do that? console.log(bases[a]); This results in ...

The error message states: "An uncaught TypeError has occurred - the object does not possess the 'jqzoom' method."

I am encountering a browser console error while working on a project involving a magento website. Specifically, I need to implement the jqzoom feature on the product view page. Here's what I have done so far: Added jQuery Included the jqzoom librar ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

Exploring the compatibility of Angular.js with iframes in Firefox

For some reason, I can't seem to get iframes to work properly in Firefox when using Angular.js routes. It's probably something simple that I'm missing, but I just can't figure it out. If you want to take a look at the code, here is a ...

Exploring Angular.js: How to propagate model changes from a child controller within an ng-repeat loop?

I'm facing an issue in my Angular application where changes made to data inside a child controller's form are not being reflected back in the parent array after saving using Restangular. I have tried using debounce to auto-save the data, but it s ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

Angular sends a POST request using $http to open in a new tab

In my Angular application, I am trying to send a POST request to a URL ./makeFile.php. This request will create a file with contents retrieved from a database query based on the data provided in the POST. When using PHP, the browser automatically opens a ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

Implement responsive data tables by setting a specific class for hiding columns

Having trouble assigning a specific class name to individual columns in datatables? It seems that when columns are hidden using the responsive extension, the desired class is not applied. Looking for a solution or workaround. Check out this example from D ...

Interactive table with ui-if functionality

Take a look at this code snippet: 1. <th ui-if="testBool">Test</th> The issue with this code is that it only includes or excludes the value 'Test', rather than the entire table header. 2. <div ui-if="testBool"> <th> ...

Is it possible to include HTML in a response when verifying emails with Node JS and Angular?

Before diving in, I want to make it clear that I have experience using APIs created in NodeJS with Angular. However, I am encountering a bit of a challenge. The issue at hand involves a function that verifies the email used during registration: exports.co ...

Anticipating outcome: row 1 column 1 (character 0) in Python

As a newcomer to the world of Python, I am currently attempting to parse data in my application using the following lines of code: json_str = request.body.decode('utf-8') py_str = json.loads(json_str) Unfortunately, when I reach this line (jso ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Comparing boolean values in React JS

I am working with a React JavaScript code in which I am iterating through a series of boolean values. The issue I am facing is that when 'data.nextrow' is false, I expect nextrow1 to also be false but it ends up being set to true instead. co ...

What is the best way to eliminate the Iframe scrollbar while ensuring that the entire page loads?

When I add an Iframe inside the contentArea, two scroll bars appear. I am looking for a way to hide the iframe scrollbar without hiding any of the external website's content. I have tried using the scrollbar="no" snippet code, but it didn&ap ...