The Angular model finally refreshes its values after a console.log() is executed

UPDATE

After further investigation, I discovered that the issue was not related to Angular itself, but rather a mistake in the update function within the node server controller. I have provided the fix below for reference, and decided to keep this question here in case it can assist others who may encounter a similar error.

ORIGINAL QUESTION

I have noticed that the Angular model does not reflect changes when a property is altered within a form. Below is the code snippet:

<section class="container" ng-controller="DjsController" ng-init="findOne()">
  <form name="djForm" class="form-horizontal" ng-submit="update(djForm.$valid)" novalidate>
    <fieldset>
      <div>.... other form fields </div>

      <div class="form-group">
        <label>Guest:</label>
        <input name="guest" type="checkbox" ng-model="dj.guest">
      </div>

      <div class="form-group">
        <label>Featured:</label>
        <input name="featured" type="checkbox" ng-model="dj.featured">
      </div>

      <button type="button" ng-click="logDj()">Log it</button>

      <div class="form-group">
        <input type="submit" class="btn btn-default">
      </div>
    </fieldset>
  </form>

Upon selecting the checkbox and submitting the form, the original model gets sent to the server without being updated. To troubleshoot, I added ng-click="logDj() to observe the model behavior. Interestingly, the model updates upon clicking the button. I am seeking a detailed explanation for this phenomenon.

Below is the included controller code:

    angular.module('djs').controller('DjsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Djs',
  function ($scope, $stateParams, $location, Authentication, Djs) {
    $scope.authentication = Authentication;

    // Clear forms
    $scope.clear = ...

    // Create new Dj
    // $scope.create = ...

    // Remove existing Dj
    // $scope.remove = ...

    // Update existing Dj
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'djForm');

        return false;
      }
      // shows original model if logDj() is not fired
      console.log($scope.dj);

      var dj = $scope.dj;

      dj.$update(function () {

        $location.path('djs/' + dj._id);

      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of Djs
    //$scope.find = ....

    // Find existing Dj
    $scope.findOne = function () {
      $scope.dj = Djs.get({
        djId: $stateParams.djId
      });
    };

    $scope.logDj = function() {
      console.log($scope.dj);
    };
  }
]);

Initially, I suspected that the issue might stem from the property not existing beforehand, but even when the property is pre-populated during retrieval, the model remains unchanged.

This peculiar behavior only seems to affect checkboxes; the values of other fields get updated as expected.

I am using the default MEAN.JS set-up generated by Yeoman, in case that information is relevant.

EDIT I have observed that this issue specifically pertains to checkboxes, while other field values are successfully updated.

Answer №1

It is recommended to initialize the object before trying to access it. The way in which the other fields are set may be unclear, possibly they are being set directly in the scope and not under the dj namespace.

$scope.authentication = Authentication;
$scope.dj = {};
.
.
.
$scope.update = function (isValid) {
    var dj = $scope.dj;

To confirm, consider adding a debugger line within the update method to inspect the dj object:

$scope.update = function (isValid) {
    debugger; // this will set a breakpoint in Chrome Dev Tools
    var dj = $scope.dj;

I hope this information proves helpful.

Answer №2

After closely tracking the data flow during the Dj model update process, I discovered the missing piece. It turned out to be related to the server.controller in node rather than Angular. While the create function worked without any issues, the update function in the controller required adjustments to align with the model. Specifically, when a PUT request is sent, the middleware populates the req with the Dj model whenever a valid ID is present in the params.

var djsPolicy = require('../policies/djs.server.policy'),
    djs = require('../controllers/djs.server.controller');

module.exports = function (app) {
  // Djs collection routes
  app.route('/api/djs').all(djsPolicy.isAllowed)
    .get(djs.list)
    .post(djs.create);

  // Single dj routes
  app.route('/api/djs/:djId').all(djsPolicy.isAllowed)
    .get(djs.read)
    .put(djs.update)
    .delete(djs.delete);

  // Finish by binding the dj middleware
  app.param('djId', djs.djByID); // HERE! };

Subsequently, this data is passed to the update function where it was crucial to ensure that the fields in the request body matched those in the Dj model. The original code snippet looked like this:

exports.update = function (req, res) {

  var dj = req.dj;

  dj.title = req.body.title;
  dj.content = req.body.content;

  dj.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(dj);
    }
  });
};

It later became apparent that the original code only included the "title" field, resulting in misleading outcomes during browser tests when changing this specific field. Hence, the updated and functional code includes all necessary fields for a successful update operation:

exports.update = function (req, res) {
  var dj = req.dj;

  dj.title = req.body.title;
  dj.image = req.body.image;
  dj.images = req.body.images;
  dj.links = req.body.links;
  dj.categories = req.body.categories;
  dj.description = req.body.description;
  dj.guest = req.body.guest;
  dj.featured = req.body.featured;

  dj.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(dj);
    }
  });
};

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

Troubleshoot the Error: EEXIST - Directory already exists at 'C:UsersPhantom' while setting up a React application[RESOLVE]

I'm trying to set up react and start my first project, but I encountered an issue during the installation process. How can I resolve this? Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom' TypeError: Cannot read propert ...

Tips for sending information from PHP to an AJAX function

Hello, I am in the process of learning PHP and I am attempting to retrieve data from a PHP file using the script below. However, I am not receiving any response: $.ajax({ type: 'POST', url: "mark_mod.php", ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

Locate the selected radio button's label

There are 25 radio button groups on my page. Each group has a specific action that needs to be performed when a radio button is selected. In order to execute the correct action for each group, I require the NAME attribute of that particular radio group. ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...

javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. How ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

Error message: Angular 7 - Running out of memory due to JavaScript heap

When attempting to run the ng serve command in my Angular 7 application, I encountered an error message stating "JavaScript heap out of memory." After researching various responses on Stack Overflow, it became clear that this issue stems from inadequate m ...

How can I connect ng-options to retrieve data from a remote JSON source?

Is it possible to use AngularJS to bind select options to a remote data source without needing an intermediate field? I'm not completely sure about this. For instance, the desired HTML would look like: <select ng-model="city" ng-options="obj for ...

Troubleshooting KuCoin API: Dealing with Invalid KC-API-SIGN Error and FAQs on Creating the Correct Signature

I want to retrieve open orders for my account using the following code snippet: import { KEY, PASSWORD, SECRET } from "./secrets.js"; import CryptoJS from "crypto-js"; const baseUrl = 'https://api.kucoin.com' const endPointOr ...

Executing a SQL query using a JavaScript variable as a parameter

I am currently working on a website form that includes a select menu populated with data from an SQL table using a loop. The form is being displayed using JavaScript scripts, which are functioning perfectly. However, I am facing an issue in the final step ...

Is it possible to modify the size of a bullet image in Javascript?

Can an image bullet style loaded via a URL be resized using JavaScript code like this: var listItem = document.createElement('li'); listItem.style.listStyleImage = "url(some url)"; listItem.style.listStylePosition = "inside"; I aim to increase ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

Oops! The page you're looking for at /api/tasks

Whenever I try to access: http://localhost:3000/api/tasks, I keep getting a "Cannot GET /api/tasks" error message. This is my server.js: var express = require('express'); var path = require('path'); var bodyParser = require('body ...

Can you explain the distinction between export/import and provide/inject in Vue3?

Can you explain the difference between export/import and provide/inject in Vue3? // parent const data = provide('data', ref(0)) // child const data = inject('data') // parent export const data = ref(0) // child import { data } from & ...

Retrieving information within the iteration

I am facing an issue with connecting to an external server named Pexels in order to retrieve photos from node.js. The problem seems to be related to JavaScript, as Pexels limits the user to download up to 40 pictures per page. https://api.pexels.com/v1/cu ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...