What are the steps to delete data in angularjs?

I attempted to eliminate the data utilizing indexOf in AngularJS. Unfortunately, the remove function isn't functioning properly. Please guide me on identifying the mistake I may be making.

JavaScript:

var app = angular.module('myApp', []);

app.controller('myCtrl', ['$scope', '$http', function($scope, $http){

$http.get('data.json').success(function(data){
    $scope.countries = data;
});

$scope.remove = function(jai) {
        var i = $scope.countires.indexOf(jai);
        $scope.countires.splice(i, 1);
};

}]);

HTML

<!DOCTYPE html>
<html lang="en>>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="p02.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">

<ul>
    <li ng-repeat='country in countries'>{{country.name}} - {{country.population}} <a href="" ng-click="remove()">&#215;</a></li>
</ul>

</body>
</html>

JSON

[
  {
    "name": "WORLD",
    "population": 6916183000
  },
  {
    "name": "More developed regions",
    "population": 1240935000
  },
  {
    "name": "Less developed regions",
    "population": 5675249000
  },
  {
    "name": "Least developed countries",
    "population": 838807000
  }]

Answer №1

Take a look at this detailed example:

(function() {

  angular
    .module("app", ["ui.bootstrap"]);

  angular
    .module("app")
    .controller("AppController", AppController);

  AppController.$inject = ["$scope"];

  function AppController($scope) {
    var vm = this;

    vm.remove = remove;

    initialize();

    function initialize(){
      vm.myArray = fetchInitialData();
    }


    function fetchInitialData() {
     return [{
        "id":0,
        "name":"Scotland"
      }, {
        "id":1,
        "name":"England"
      }, {
        "id":2,
        "name":"Wales"
      }, {
        "id":3,
        "name":"Northern Ireland"
      },{
        "id":4,
        "name":"France"
      },{
        "id":5,
        "name":"Italy"
      },
      ];
    }
    
    
    function remove(country){
      var index = vm.myArray.indexOf(country);
      vm.myArray.splice(index,1);
    }



  }


})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1b3bebea5a2a5a3b0a191e2ffe2ffe6">[email protected]</a>" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0abafbfa8a39ae8f4e8f4ee">[email protected]</a>" data-semver="2.2.4" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385a57574c4b4c4a5948780b160b160f">[email protected]</a>" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15747b72607974673b7f6655243b233b24">[email protected]</a>" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
  <script data-require="ui-bootstrap@*" data-semver="2.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="app.js"></script>
</head>

<body ng-controller="AppController as vm">
  
<div>
      <div class="table-responsive">
          <table class="table table-bordered">
              <thead>
                  <tr>
                      <th class="col-xs-1">ID</th>
                      <th class="col-xs-5">Country</th>
                      <th class="col-xs-6">Change</th>
                  </tr>
              </thead>
              <tbody>
                  <tr ng-repeat="item in vm.myArray">
                      <td class="text-center">
                          {{item.id}}
                      </td>
                      <td>
                          {{item.name}}
                      </td>
                      <td>
                        <button class="btn btn-danger" ng-click="vm.remove(item)">Delete</button>
                      </td>
                   </tr>
               </tbody>
          </table>
     </div>
</div>


</body>

</html>

Answer №2

Include the country parameter in your remove function

<ul>
    <li ng-repeat='country in countries'>{{country.name}} - {{country.population}} <a href="" ng-click="remove(country)">&#215;</a></li>
</ul>

Answer №3

To avoid duplicates, make sure to include track by $index and pass the index directly in the remove function instead of using the indexOf function.

In your HTML code, it should be written as:

<li ng-repeat='country in countries track by $index'>{{country.name}} - {{country.population}} <a href="javascript:void(0)" ng-click="remove($index)">&#215;</a></li>

As for the function, it should be:

$scope.remove = function(idx) {
    $scope.countires.splice(idx, 1);
};

Please let me know if this information is helpful to you.

Answer №4

To properly remove an item, remember to include the parameter in your function call like ng-click="remove(country)"

  <ul>
        <li ng-repeat='country in countries'>{{country.name}} - {{country.population}} <a href="" ng-click="remove(country)">&#215;</a></li>
    </ul>

For a working example, check out this demo

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

Having trouble showing my Google map using canvas

Can anyone help me with this issue that I'm facing? I am working on a JavaScript web page and trying to show a Google map (Google API) along with a canvas tag in the html body. Currently, the map and canvas are only displaying separately. https://i ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

Initiate modal from sub-component

Right now, I am developing a vue application with a structure that closely resembles the following: <div class="characters"> <Character v-for="character in this.charactersToSearch" :key="character.id" :name="cha ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Making an Ajax request to retrieve progress information by utilizing IProgress

I have encountered an issue with my code involving 2 ajax API calls. One call fetches data through a lengthy process, while the other retrieves progress values using the IProgress interface and runs every 5 seconds. The value from ReportProgress successf ...

Enhance User Experience by Updating Status on Checkbox Selection in PHP

I am working with a datatable and I have created a table using datatables. How can I change the status field when a checkbox is clicked? The default status is 'before', but when the checkbox is clicked, it should update to 'after' in th ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Exporting the output of an AngularJS directive, specifically an ng-repeat, into an individual downloadable HTML file - a comprehensive guide

Can Angular be used to download the content of a div (specifically with ng-repeat directive) in a new HTML file? I attempted to do this: var content = 'file content'; var blob = new Blob([ content ], { type : 'text/html' }); $scope.ur ...

Flipping back and forth between two images within a single HTML file

I am looking to customize my top navbar for two different webpages, the root URL (/) and firstpage (/firstpage). The top navbar contains 2 images that I want to switch based on which page the user is currently on. Here is the code snippet: <img class=" ...

Is the background image slowly disappearing?

Instead of using the background property for a background image, I have opted for a different style. Here is how I implemented it: <div id="bg"> <img id="bgChange" src="image/image.jpg" /> </div> This is the corresponding CSS code: ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Deleting an item from an array using Mongoose

Looking to eliminate an element from an array in a document using mongoose. Example entry: { _id: "12345", folder: { name: "Folder1", files: [ { fileName: "File 1", fileID: "6789", folderID: "12345" } ] ...

Unable to authenticate through LinkedIn

On my website, I am attempting to retrieve the user's first name, last name, and email using LinkedIn. Here is what I have done so far: In my LinkedIn App settings, under the Default Scope (OAuth User Agreement), I have selected the following options ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...

Error: Unable to access the property '_locals' of an undefined value

I have been experimenting with nodejs on my Ubuntu 16.04 system, where I successfully installed Node and npm. However, I encountered an error stating "TypeError: Cannot read property '_locals' of undefined" while trying the following code: var e ...

Preventing script-src with Content Security Policy in a React application

Everything seemed to be running smoothly with my create-react-app, but out of nowhere, my console started showing this error message: Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”). (this occur ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

What is the best way to insert a line break into every row of the table I'm displaying?

My current project involves building a web scraper that successfully prints a table, but the formatting of the table is less than satisfactory. I've experimented with a few solutions so far: 1) const people = [...peopleList].map(personEntry => pe ...