Encountering difficulties with updating an object in Angular

Currently, I have the ability to generate objects and store them in a rails database using a json api. The application is a basic todo list where adding an object places it into the todo list above the input fields. Furthermore, I can access all objects on the index view and display them as a list of my todo items.

Upon selecting a checkbox next to each todo item, it is intended to change its :done attribute to true. This would mean that the item should no longer be displayed after clicking a "Clear" button which triggers the clearCompleted function.

Shown below is my JavaScript code:

angular.module("Todo", ["ngResource"])

function TodoController($scope, $filter, $resource) {
  Todo = $resource("/todos.json", {id: "@id"}, {update: {method: 'PUT'}})
    $scope.todos = Todo.query()

  $scope.getTotalTodos = function () {
      return $scope.todos.length;
  };

  $scope.clearCompleted = function () {
    Todo.save({done:true})
    $scope.todos = $filter("filter")($scope.todos, {done:false});
};

  $scope.addTodo = function () {
    entry = Todo.save({title:$scope.newTodo.title, importance:$scope.newTodo.importance, description:$scope.newTodo.description, done:false})
    $scope.todos.push(entry);
    $scope.newTodo.title = '';
    $scope.newTodo.importance = '';
    $scope.newTodo.description = '';
  };

}

The issue lies in creating a new todo item with the attribute of :done => true instead of updating the existing record in the database. This discrepancy occurs because within the clearCompleted function, we are seemingly creating a new object rather than modifying an existing one.

How can I properly update the database record?

Answer №1

Avoid using Todo.save({}) to modify a todo item, as it will create a new object instead of updating the existing one.

Instead, consider the following approach:

 Todo = $resource("/todos.json", {id: "@id"}, {'save': {method: 'PUT'}})
 $scope.todos = Todo.query();
    var todo =  todos[0];//Identify the specific todo you want to update
    todo.done = true;
    todo.$save();

Make sure to include a parameter for the todo key in your save URL if needed.

Learn more about using $resource 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

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

Customize Your Calendar: A Guide to Disabling Dates with Pikaday.js

Wondering how to disable specific days on a calendar? Look no further! Here's a solution using the `disableDayFn` option from Github: disableDayFn: callback function that gets passed a Date object for each day in view. Should return true to disable s ...

Error: $controller does not function as a controller within another controller

I recently started learning Angular JS and attempted to call one controller within another, but encountered the following error: ionic.bundle.js:21157 TypeError: $controller is not a function at new <anonymous> (http://localhost:8080/itravel/www/js/ ...

Using AngularJS $http.put method with ASP.NET MVC controller may encounter issues and not function as expected

Attempting to develop a straightforward webpage for sending data to the server using $http.put. Script code <script> var myApp = angular.module("myApp", []); myApp.controller("HttpPostController", function ($scope, $http) { $scope.SendHttpPost ...

Is there a way to determine if the tab has been muted by the

Chrome enables users to easily mute tabs by right-clicking on them and selecting Mute Tab. I am curious about whether there is a method to detect when a user has muted the tab. In other words, I am interested in knowing if it's possible for a website ...

Discovering the children of the target DOM element in React

Imagine you have an HTML unordered list that you want to turn into a React element: <ul id="mylist"> <li><a href="">Something</a></li> <li><a href="">Another thing</a></li> <li><a ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

Issues with React and Recharts legend functionality causing disruptions

I am currently experimenting with React and Recharts to build a stacked and grouped bar chart. This is my first experience using Recharts, and I have encountered an issue with the legend functionality. I would like the legend to toggle both graphs within e ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Error in Ruby on Rails: View cannot locate the path for Collection routes

I have included a collection route with POST method in my routes file. resources: curated_items do collection do post 'duplicate' end end However, I am unable to locate the path for the 'duplicate' prefix in my view.v ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Even though a variable has been assigned a value, it continues to retain its default value

One of the variables in my Model is initially set to null angular.module('qbs.models').service('loginModel', function () { this.name = 'loginModel'; var data = { //....... loggedIn: null, loggedOut: null //. ...

Lambda script for Amazon Alexa Skill is not functioning as expected

I am currently developing a Lambda function for an Amazon Alexa skill using NodeJS. For those unfamiliar, Alexa is a cylindrical speaker that responds to voice commands, and a "skill" is essentially a voice-operated app for the device. This particular func ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Is there a way to transmit a value from a page item on the client side to the server side in Oracle Apex without needing to submit the form?

I implemented a JavaScript function to capture the unique ROWIDs of selected rows in the GRID and send them to a specific page item. var gridView = apex.region("emp").call("getCurrentView"), selectedRecords = gridView.getSelectedRec ...

Leveraging a third-party UI component within an AngularJS directive

Have you heard of the npm package called smooth-dnd? If not, here is a link to its GitHub repository: https://github.com/kutlugsahin/smooth-dnd#readme This package is compatible with React, Angular, and Vue.js. However, my current project is built using ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...