Troubleshooting AngularJS application by Manipulating List Items

Having trouble debugging Angular lately. It feels like things are breaking and fixing themselves magically. For instance, I had an ajax call to delete a "site" which was working fine until I decided to add some code to remove it from the list as well. Now, the id comes through as null and my onClick() breakpoint in Chrome never gets hit. I'm using MVC5 and Angular.

<table class="table">
<tr>
    <th>
        Value
    </th>
    <th></th>
</tr>

<tr ng-repeat="site in sites">
    <td>
        {{site.Value}}
    </td>
    <td>
        <button id="delete-{{site.Id}}" class="btn btn-primary" ng-click="deleteSite(site.id)">Delete</button>
    </td>
</tr>

Angular controller

ngApp.controller('siteController', ['$scope', '$http', '$location', function ($scope, $http, $location) {

$http.post(ROOT + '/Site/LoadAll/')
          .success(function (result) {
              $scope.sites = result;
          }).
          error(function (data, status, headers, config) {
              // log to console?
          });

$scope.deleteSite = function (id) {
    //$http.post(ROOT + 'SiteList/Delete/', JSON.stringify(id)) //null id
    //$http.post(ROOT + 'SiteList/Delete/', id) //Invalid JSON primitive: 5f6d794f-bf13-4480-9afd-3b10d7b6ae32.
    //$http.post(ROOT + 'Site/Delete/', { id: id } )
    $http.post(ROOT + '/Site/Delete/' + id)
        .success(function (result) {
            // log to console?
        }).
        error(function (data, status, headers, config) {
            // log to console?
        });

    for (var i = $scope.sites.lenght - 1; i >= 0; i--)
    {
        if ($scope.sites[i].id == id)
        {
            $scope.sites.splice(i,1)
        }
    }
};}]);

Server controller

public JsonResult Delete(Guid id)
    {
        try
        {
            _siteService.Delete(id);
            return Json("OK", JsonRequestBehavior.AllowGet);
        }
        catch (Exception e)
        {
            return Json("Error" + e.Message);
        }

    }

Can anyone identify an issue here? How do you go about debugging your Angular applications?

Answer №1

Looks like there is a need to debug a combination of JavaScript, HTTP requests, and ASP.NET MVC model binding in this scenario.

To tackle the JavaScript issue, consider adding some console.log statements. When using Chrome for development and debugging, try including a

console.log('site', i, id, $scope.sites);
within your "splice loop" to verify the expected result.

Monitoring HTTP traffic can be done through Chrome's network tab or by using tools like Fiddler2. It may require some experimentation to grasp initially, but once understood, it becomes fairly simple. Pay particular attention to the form values in the request, ensuring that the key id contains the site's ID value.

In your ASP.NET MVC application, consider setting a breakpoint at the first { line of your action method. Then, examine the id variable to ensure it holds the expected value.

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

Looking for a way to execute code exclusively when the 'other' option is chosen? Let's tackle this challenge with Javascript and swig

I am looking to utilize swig (my chosen templating engine) for incorporating JavaScript code that will only display when the user selects the 'other' option from the select menu. <div class="form-group"> <select class="custom-select"&g ...

What is a callback function tied to a specific URL?

I need to implement a functionality in my web application where users can click on a link within a datatable, which will then load a new table on a separate page. This new table should only display rows that have the same id as the row that was clicked on ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

Determining if a variable has been defined in JavaScript

In my JavaScript code, I declare global variables named with the prefix "sld_label" where "label" can be any string. These variables are initialized as objects that contain a function called setval. Now, I have a function that receives a label in a string ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Error message in Material-UI TextField not displaying when state is updated using Object.assign technique

Currently, I am facing an issue with validating a login form and displaying errors dynamically. These errors are passed as props from the child component. The problem arises when I set the errors object using Object.assign - the errorText does not show up ...

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...

Leveraging Array.map within Angular Interpolation

Is it possible to achieve the following in HTML using Angular 2+? {{ object.array.map((o) => o.property ) }} Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique? ...

Compel the browser to initiate a reflow by adjusting the CSS

I am currently in the process of building a responsive image slider without relying on jQuery, using CSS3 transitions. The setup is quite simple: there's a viewport with a UL inside, containing relatively positioned LIs that are left floated. Howeve ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Is there a delay following the click on the file upload button?

Whenever I attempt to choose a file for upload by clicking on "Select File" (input type=file), there seems to be a lag between the moment I click the button and when the selected file appears next to the button. It almost seems as if the browser is attempt ...

What is the most effective way to implement Promises within a For loop?

const wiki = require('wikijs').default; const { writeFileSync } = require("fs") const dates = require("./getDates") //December_23 for (let i = 0; i < dates.length; i++){ wiki() .page(dates[i]) .then(page => p ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

What strategies can be employed to enhance the natural movement of dots on my HTML canvas?

Check out my code pen here I'm looking for feedback on how to make the movement of the canvas dots more fluid and liquid-like. I've experimented with restricting the direction for a certain number of renders (draw()), which has shown some impro ...

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

Testing the equality of nested arrays: A step-by-step guide

My maze generator creates walls for each "cell", resulting in duplicate walls - such as the left wall of one cell being identical to the right wall of the adjacent cell. I have managed to convert the maze data into a different program where it is stored in ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

Angular $watch function not reflecting changes in the user interface

My $watch function is updating the model, but the bound controls in the UI are not reflecting the changes. Here is a screenshot of the updated model. https://i.stack.imgur.com/0ISg5.png The UI code looks like this: <form method="post" action="" role= ...