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

Difficulty in transferring a variable from my JavaScript file to my PHP file

Currently, I am utilizing the Instascan API to scan QR codes with the intention of sending the scanned content to my PHP file. However, regardless of whether I use POST or GET methods, the PHP file does not seem to recognize them and keeps expecting either ...

Unexpected Error with Background Position Variable

Hello, I am attempting to create an animated background effect that moves up and down using the .animate() and .hover() methods in jQuery. Within my DOM, there is a div with id="#menu" containing a UL list where each item has a background positioned at dif ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

Session data in ExpressJS is not being stored in the cookie

There are plenty of questions on this topic, but unfortunately, I haven't found any answers that solve my issue. I'm using Chrome with ExpressJS and VueJs 3 to build a simple application where users can "login" and access another page. All I wan ...

a class instance in Java Script returned as undefined

Having sought resolution for this question once before, I find myself revisiting it as the issue still persists. My apologies for the duplicate post. The first file in question is block.js: class Block{ constructor(timeStamp, lastBlockHash, thisBloc ...

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

Arrange the row information in the MUI DataGrid in order to prepare it for exporting to CSV or Excel

Is there a way to organize row data for exporting to CSV or Excel with the MUI DataGrid? Take a look at my code snippet for the toolbar. slots={{ noRowsOverlay: NoDataComponent, noResultsOverlay: NoDataComponent, toolbar: ( ...

Endless cycle in Vue-Router when redirecting routes

I need advice on how to properly redirect non-authenticated users to the login page when using JWT tokens for authentication. My current approach involves using the router.beforeEach() method in my route configuration, but I'm encountering an issue wi ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

Unable to adjust dimensions with CSS width and height properties

I'm currently working on developing an online game with a login screen inspired by Paper.io. I have created the username input and play button, but there seems to be an issue with the width and height specified in the CSS file for the input field. Eve ...

Adjust the settings of a CSS element

Apologies as I am still new to this and struggling to implement the correct code. I am attempting to modify the background color of a custom marker in leaflet.js. Essentially, I need to adjust the CSS element's value. I have the CSS code and how I am ...

Check out the new Bootstrap 5 form when it's successfully validated

I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}' <script> (function () { 'use strict' const forms = document.querySelectorAll(&apos ...

Firefox Cookie Expiry Date Automatically Set to One Week in Default Settings

I recently encountered an issue while trying to create a cookie that would persist for a year. Interestingly, the code I used worked perfectly on Chrome, as I could verify by checking the "Storage" in the dev tools. However, when I tried the same code on F ...

Center the popover over the element

I am in the process of creating a resource map using SVGs. My goal is to display a popover in the center of the element when a user clicks on it. However, due to CSS rotation of the map, the traditional techniques such as the one mentioned here have not be ...

Storing data in the browser's local storage using jQuery without requiring any CSS

I have a form that receives data and I am trying to save the first two pages of received data into localStorage: <form id="myForm" method="post"> Font Size (px): <input id="fontsize" type="text" name="fontsize" /> </form> <s ...

Utilize the setInterval method to repeatedly call the random function

Can someone assist me in setting a time interval of about 1 second for this function? function random_imglink(){ var myimages=new Array() //insert your desired random images below myimages[1]="/documents/templates/bilgiteknolojileri/standalo ...