Updating the AngularJS view following a deletion process

I have a web application developed using AngularJS and Rails that carries out RESTful operations like create, read, and delete.

After deleting an item, I need to refresh the page and update the view asynchronously. However, I am facing challenges in implementing this due to an error:

Cannot read property 'success' of undefined

Here is a snippet from my app.js file:

//= require angular-rails-templates
//= require_tree .


angular.module('d-angular', ['ui.router', 'templates'])

// Set routing/configuration
// ------------------------------
.config(['$stateProvider', '$urlRouterProvider',

    // Setting up state providers
    function($stateProvider, $urlRouterProvider) {$stateProvider

        // Home state
        .state('home', {
          url: '/home',
          templateUrl: 'home.html',
          controller: 'MainCtrl',
          resolve: {
              listPromise: ['lists', function(lists){
                return lists.getAll();
              }]
          }
        })

        $urlRouterProvider.otherwise('home');
    }
])


// Lists factory section
.factory('lists', ['$http',

    function($http){
        var o = { lists: [] };

        o.getAll = function() {
            return $http.get('/lists.json').success(function(data){
                angular.copy(data, o.lists);
            });
        };

        o.get = function(id) {
          return $http.get('/lists/' + id + '.json').then(function(res){
            return res.data;
          });
        };

        o.create = function(post) {
          return $http.post('/lists.json', post).success(function(data){
            o.lists.push(data);
          });
        };

        o.delete = function(id) {
            $http.delete('/lists/' + id + '.json');
        }

        o.addWord = function(id, word) {
          return $http.post('/lists/' + id + '/words.json', word);
        };

        o.deleteWord = function(id, word) {
            $http.delete('/lists/' + id + '/words/' + word + '.json');
        }

        return o;

    }
])


// Main controller section
.controller('MainCtrl', ['$scope', '$stateParams', 'lists', '$http',

    function($scope, $stateParams, lists, $http) {

        $scope.lists = lists.lists;

        $scope.list = lists.lists[$stateParams.id];

        $scope.addList = function(){
            if(!$scope.title || $scope.title === '') { 
                return;
            }

            lists.create({
                title: $scope.title,
                date: new Date().toJSON().slice(0,10),
            });

            $scope.title = '';
        };

        $scope.deleteList = function() {
            lists.delete($scope.list.id).then(function(){
                $scope.lists.splice(index, 1)
            }); 
        };

        $scope.addWord = function(){

                lists.addWord($scope.list.id, {
                    title: $scope.word,
                    date: new Date().toJSON().slice(0,10),
                })
                .success(function(word) {
                    $scope.list.words.push(word);
                });
            });
        };

        $scope.deleteWord = function(word_id) {
            lists.deleteWord($scope.list.id, word_id);
        };


    }

]);

View Section:

<div ng-controller="MainCtrl">

  <form ng-submit="addList()">
    <input type="text" ng-model="title" placeholder="Enter list"></input>
    <button type="submit">Add</button>
  </form>

  <select ng-model="list" ng-options="list as list.title for list in lists">
      <option value="">Select List</option>
  </select>

  <form ng-submit="deleteList()">
    <button type="submit">Delete</button>
  </form>

  <hr>

  {{list.id}}

  <form ng-submit="addWord()">
    <input type="text" ng-model="word"></input>
    <button type="submit">Add</button>
  </form>

   <div ng-repeat="word in list.words">
      {{word.title}}
      {{word.id}}

      <form ng-submit="deleteWord(word.id)">
        <button type="submit">Delete</button>
      </form>

  </div>

Answer №1

Could the issue be related to your factory function not returning the value from $http.delete()? To fix this, make sure to include a return statement in your factory function:

    o.removeWord = function(id, word) {
        return $http.delete('/lists/' + id + '/words/' + word + '.json');
    }

Next, in your controller, you can utilize .success() method like so:

    $scope.deleteWord = function(word_id) {
        lists.removeWord($scope.list.id, word_id)
             .success(...);
    };

Answer №2

Expanding on my previous response

If you already have a function called o.getAll, you can simply invoke it within the success callback of your code.

o.deleteWord = function(id, word) {
    return $http.delete('/lists/' + id + '/words/' + word + '.json')
    .success(function(response){ 
        return o.getAll(); 
    }):
}

I suggest placing this logic within the o.deleteWord function. Additionally, in your rails controller, make sure to include `respond_with Word.all` after deleting your model. This is important for updating the page as it listens for an updated words.json. Consider adding something like the following:

  def destroy
    Word.delete(params[:id])
    respond_with Word.all
  end

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

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Leverage Jquery within the div element to manipulate the data retrieved from a post ajax request

On my one.jsp page, I have the following post code: $.post("<%=request.getContextPath()%>/two.jsp", { vaedre: fullDate} ,function(result){ $("#theresult").append(result); }); This code generates the followi ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

What is the best way to transmit two variables in a single message with Socket.io?

My goal is to send both the clientid and username through the socket communication. client.userid = userid; client.username = username; client.emit('onconnected', { id: client.userid, name: client.username }); I attempted this approach, how ...

A guide on personalizing HTML for Django forms

I have implemented an HTML template on my website and need to capture information for my Django backend. Specifically, I am trying to extract the email address from this section of code: <input type="text" placeholder="Email" value="" style="height: 30 ...

Creating a function that counts the number of times a button is clicked

I want to have the "game" button appear after the user clicks the "next-btn" 2 times. Once the multiple choice test has been completed twice, I'd like the game button to show up and redirect the user to a separate HTML page called "agario.html." I&ap ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

Gradual disappearance of preloader as the page loads

I'm facing an issue with setting a gif as a website preloader. Despite trying different JavaScript solutions, the preloader remains visible even after the page has finished loading. $(window).on("load", function() { $(".loading").fadeOut("slow"); ...

Exporting modules in Node.js allows you to use functions

Can you explain why this code snippet is successful: exports.foo = 'foo'; var bar = require('./foo'); console.log(bar); // {foo: 'foo'} While this one fails to produce the desired output: var data = { foo: 'foo' ...

I am currently struggling to make the userID route parameter function correctly with react-router-relay

I've been diving into the world of React Relay and GraphQL with react-relay-router, but I'm having trouble getting the params in my routes to function correctly. Specifically, I'm struggling with the "/Maps/:userID" route. Let me share my r ...

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

- The click function is failing to work after an ajax call [Potential event delegation problem]

I have a webpage where I update the contents of an unordered list using $.get() every 5 seconds. The issue I am facing is that the click function for the list items is not working properly. Even though the list items are being updated correctly, there se ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Is there a feature in Angular 2+ (specifically Angular 7) that allows for comparing code differences

Is there a code comparison component or plugin available for Angular 2+ (specifically Angular 7) that can compare two separate text files? In our current AngularJS application that we are upgrading, we currently use Ace-Diff and it works effectively. Howe ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Encountering RangeError with the Number() function on my express.js server

I'm working with an HTML form that looks like this: <form class="" action="/" method="post"> <input type="text" name="num1" placeholder="First Number"> <input type= ...