What is the reason behind AngularJS consistently selecting the first TD cell?

I'm a beginner in AngularJS and I'm testing my skills by creating a small game.

Here's the table structure I have:

<table class="board">
<h1>Table</h1>
<input type="number" ng-model="val"><button ng-click="ctrl.foo(val)">PRESS</button>
    <tr ng-repeat="tr in ctrl.arr">
        <td ng-repeat="td in ctrl.arr" ng-click="ctrl.getIndex(tr, td)">{{ctrl.sign[$parent.$index][$index]}}</td>
    </tr>
</table>

Below is the snippet of code used to mark the cell you click on:

this.foo = function(size){

        this.arr = [];
        for(var i = 0; i < size; i++){
            this.arr.push(i);
        }
    }
    this.getIndex = function(tr, td){

        this.sign = 'X';

        console.log(tr, td);
    }

I am facing an issue where clicking on any cell only marks the first cell. Can anyone help me understand what mistake I might be making?

If possible, please check out the example here

Answer №1

The issue lies in the fact that you are assigning ctrl.sign as a variable in ctrl.push, but then treating it as a 2d array when referencing it within the html code.

The presence of 'x' in the first column can be illustrated through a simple example (though the reason for this behavior is not entirely clear, it may be related to how javascript handles variables)

var test = 'x';
console.log(test[0][0]); //displays 'x'
console.log(test[0][1]); // displays undefined
console.log(test[1][1]); // results in a type error

To resolve this in your code, we need to create a proper 2d array and modify your existing method for inserting the 'x'. We will adjust foo to generate/populate the 2d array, while push will handle the actual insertion:

this.foo = function(size) {

    this.arr = [];
    for (var i = 0; i < size; i++) {
        this.arr.push(i);
        //populate our 2d array
        this.sign.push([]);
        for (var g = 0; g < size; g++) {
           this.sign[i].push(''); 
        }
    }
}
this.push = function(parent, index) {
   this.sign[parent][index] = 'X';
   console.log(parent, index)
}

You can also update arr with sign in your ng-repeats at this stage. For a functional example, please refer to the working jsfiddle here.

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

Creating a secure countdown timer on the server side: Best practices

I've developed a quiz application that features a countdown timer of 300 seconds for answering 10 questions. Once the time is up, the scores are sent to the server where they are compared with the answers and then stored. However, my main concern is t ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

Exploring JSON data with ReactJS

I am experiencing issues with populating a table with data imported from a JSON file. The error message I'm receiving is: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {list}). If you intended to render ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

JavaScript validation for radio buttons that are grouped together

Need help with a JavaScript validation issue regarding grouped radio buttons named optionRadios1 to 5. I'm trying to validate them before submitting the form, but my code isn't working as expected and still allows the form submission. Below is t ...

Validation of user input alongside input masking using jQuery

One issue that I am encountering is that form inputs with assigned masks (as placeholders) are not being validated as empty by jQuery validation. I am using: https://github.com/RobinHerbots/jquery.inputmask https://github.com/1000hz/bootstrap-validator ...

Ways to trigger a Vue.js method after a delay of 500 milliseconds

Currently, I am developing a search system that triggers an ajax call with every key press. However, I would like to implement a delay of 500ms before the ajax call is made after typing begins. Any ideas on how this can be achieved? ...

A helpful tip for creating line breaks within a Vue JS v-for loop using CSS

I am looking to arrange the names in alphabetical order when a list item is clicked. My tools of choice are Vue.js and Flex Grid. The list item I am working with is called ListAll, When clicking on ListAll, I want to display all the records grouped by na ...

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

Unable to access and process POST parameters sent via ajax in PHP

When passing two parameters in the send method to index.php, an error "Undefined index" is returned by PHP. echo $_POST['fname']; submit.addEventListener("click", function(e){ e.preventDefault(); var xhr = new XMLHttpRequest(); xhr. ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

jQuery Alert for Double-Checking Email Entry

Is it possible to create a simple alert pop-up using jQuery if the user does not enter the correct email address in the second email input form? Below is my current code: <div id="reservation-request"> <form method="post" action="test.php ...

Step-by-step guide on deleting an entire row from a PHP webpage

I have removed a row from the database, but now I need to also remove it from the interface on my PHP page. Any suggestions or assistance would be greatly appreciated. Here is a snippet of mypage.php: <tr> <td><?php echo $row[' ...

How can we protect against CSRF attacks?

My typical approach involves using AJAX to input data into a MYSQL database like this: $.ajax({ url: "writescript.php", type: "POST", data: { data : mydata,//this could be anything }, success: function (html) { //do something ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

Unlock the Power of Sockets in JavaScript and HTML

How can I work with sockets in JavaScript and HTML? Could HTML5 features be helpful? Are there any recommended libraries, tutorials, or blog articles on this topic? ...

Just getting started with JavaScript and running into trouble creating an array of image objects using an array of strings

I am struggling to accurately describe my issue, making it difficult to find a solution. I have an array called tempData generated from a text file that I want to reference with variables of the same name as the strings in the array. var red = new Image ...

Filtering JSON data with JavaScript

Looking to group data in AngularJS using UnderscoreJS. Here is the JSON data: data = [ { "Building*": "Building A", "Wing*": "Wing C", "Floor*": "Floor 3", "Room Name*": "Room 3", "Room Type*": ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...