Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty.

This situation has left me puzzled. Below is the code snippet I am working with:

Controller:

function appController($scope) {
    $scope.players = [];
    var playercount = 0;

    $scope.addPlayer = function(playername) {

        $scope.players.push({name: playername, score: 0, id: playercount});
        playercount++;
    }

    function getIndexOfPlayerWithId(playerId) {
        for (var i = $scope.players.length - 1; i > -1; i--) {
            if ($scope.players[i].id == playerId)
                return i;
        }
    }

    $scope.removePlayer = function(playerId) {
        console.log("remove");
        var index = getIndexOfPlayerWithId(playerId);
        $scope.players.slice(index, 1);
    }
}
appController.$inject = ['$scope'];

HTML:

...
<table id="players">
        <tr ng-repeat="player in players">
            <td>{{player.name}}</td>
            <td>{{player.score}}</td>
            <td><button ng-click="removePlayer({{player.id}})">Remove</button></td>
        </tr>
    </table>
...

Answer №1

Avoid using curly brackets ({{ }}) in the ng-click statement. Instead, try utilizing this format:

<button ng-click="removePlayer(player.id)">Delete</button>

Answer №2

ng-repeat generates a new scope, causing it to not recognize removePlayer. You can resolve this issue by implementing the following code:

<table id="players">
    <tr ng-repeat="player in players">
        <td>{{player.name}}</td>
        <td>{{player.score}}</td>
        <td><button ng-click="$parent.removePlayer({{player.id}})">Remove</button></td>
    </tr>
</table>

For more information, visit https://groups.google.com/forum/?fromgroups=#!topic/angular/NXyZHRTAnLA

Answer №3

In the context of ng-repeat, a separate scope is created and the outer controller's scope cannot be directly accessed. However, by leveraging JavaScript's use of true objects, you can achieve the desired functionality like so:

<tr ng-repeat="player in players">
    <td>{{player.name}}</td>
    <td>{{player.score}}</td>
    <td><button ng-click="player.removePlayer()">Remove</button></td>
</tr>

Prior to this code snippet, during your controller initialization, you can assign the "removePlayer" function to each player object. This way, you can indirectly access the outer controller while customizing the functionality as needed.

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

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

Leverage the variable from one function in a different function within Three.js using Javascript

After loading an obj file using three.js, I attempted to obtain the 'X' position of its vertices and save it in a variable named 'pos' inside the objloader function within the init() function. My goal was to access this variable's ...

Grails: the choice between a unified application or separate back-end and front-end apps

We are beginners in the world of Grails and have some concerns that we want to address: Issues related to scalability Utilizing the same back-end for multiple applications Do you think it's a good idea to stick with just one Grails application, ...

What is the process for dynamically altering the method in a class?

Is there a way to dynamically modify the changeThis method by substituting it with the value of a radio element? For example, if I select event1, the method should be switched to Class.event1() <input type="radio" class="radio-input" ...

What steps can I take to personalize Material UI within a React application?

As someone who is new to this UI framework and React, I have been tasked with developing an application that requires more design patterns. I specifically chose a framework that does not depend on jQuery code. However, I am facing challenges when it comes ...

Strategies for efficiently retrieving delayed ajax data to display in a Rails view

When working with an API action that takes around 10 seconds to retrieve data, I typically use an alert to ensure the data is successfully fetched. However, my main concern is how to effectively transmit this data to a Rails view for displaying purposes. B ...

Is it possible to dynamically change an ngModel value directly from the component?

I'm currently immersed in an Angular project and my initial file setup was like this: dog.ts: export interface Dog { name: string; age: number; breed: string; } dog.component.ts: import { Dog } from '../dog'; @Component({ //setup ...

Error not caught: AngularJS module error

Initially, I was hesitant to ask this question, but after struggling for two hours without any success, I've decided to seek some assistance. I'm trying to integrate the ngResource module into my application. Prior to this, everything was functi ...

What's the best way to adjust text color to black or white for maximum contrast when the background changes?

Currently, I am attempting to replicate the email element found on this website: .custom-blend-mode { mix-blend-mode: difference; } Although I have managed to make it work, it results in a change to the opposite color. Ideally, I would like it to remai ...

Tips for preventing a page refresh using HTML, JQuery, AJAX, and PHP

I need assistance with transferring the value of a selected radio button to a PHP session variable using Javascript/AJAX. Everything seems to be working fine, except that the page refreshes each time. Is there a way to prevent this from happening? Below i ...

How can I make my webpage unselectable except for specific content within a div using CSS and JavaScript?

During a live editing session, I am looking to make only specific portions of the page selectable. Can someone provide guidance on how to disable selection for everything except within a particular div? ...

implementing a timestamp in a specific timezone with Vue.js

Utilizing a timestamp attribute, I have successfully implemented the display of the current time and date on my webpage. Is there a way to showcase this information in a specific time zone? I am looking to present it in the ZULU timezone, which remains st ...

Ways to retrieve and update the state of a reactjs component

I'm facing an issue with modifying a React JS component attribute using an event handler. export default interface WordInputProps { onWordChange:(word:string) => void firstLetter:string disabled?:boolean } These are the props for my co ...

The Heatmaps.js script encountered an Uncaught ReferenceError

I am currently utilizing the heatmaps.js library along with the Google Maps API to showcase a map with a heatmap overlay. So far, I have successfully displayed the map and retrieved the necessary data from the database. However, I'm encountering an is ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...

Exploring a JSON Object with Nested Data

I am trying to recursively parse a JSON object in JavaScript. Below is an example of the JSON structure: const obj = { tag: 'AA', type: 'constructed', value: 'ABCD1', child: [ { tag: 'BB', ty ...

Trouble Connecting Local Database with PG NPM Package

I'm encountering issues with using the pg package on my computer. I've attempted to execute the following code: var pg = require('pg'); var con_string = "postgres://user:password@localhost:5432/documentation"; var client = new pg.Clie ...

Tips for creating a universal function to connect html elements in AngularJS

As a beginner in angularJS, I come with prior experience writing common functions for binding html controls in JS. However, I am looking to apply the same approach in angularJS. I understand the angular way of binding html controls, but my goal is to str ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...