A more detailed explanation of Angular's dot notation

I came across a solution for polling data using AngularJS here on stackoverflow.

In this particular solution (shown below), a javascript object is used to return the response (data.response). I tried replacing the data object with a simple javascript array, but it resulted in not working. I am curious as to why I need to use dot notation and why a single array doesn't suffice. It would be great if someone could provide links or explanations supported by examples.

app.factory('Poller', function($http, $timeout) {
  var data = { response: {}, calls: 0 };
  var poller = function() {
    $http.get('data.json').then(function(r) {
      data.response = r.data;
      data.calls++;
      $timeout(poller, 1000);
    });      
  };
  poller();

  return {
    data: data
  };
});

To summarize my goal (what I aim to understand): Can

var data = { response: {}, calls: 0 };
be replaced with var data = {};, setting response.data directly to data = r.data, and return {data: data};? Why must dot notation be relied upon?

Answer №1

Imagine a scenario where we make a change to the factory in the following manner:

app.factory('Poller', function($http, $timeout) {
  var d = {};
  var poller = function() {
    $http.get('data.json').then(function(r) {
      d = r.data;
      $timeout(poller, 1000);
    });
  };
  poller();

  return d;
});

Within the controller, the line $scope.data = Poller; assigns the d object to $scope.data, establishing the following object relationship upon initialization:

$scope.data -> d -> r.data

Each time poller() is invoked after 1 second, a new object replaces d, resulting in the updated object relationship as follows:

$scope.data -> d* -> r.data (where d* represents a new object)

As a result, AngularJS's data binding becomes disrupted because it cannot track back to r.data due to d* being an entirely different object with a distinct prototype.

By utilizing dot notation, the object relationship remains consistent post-initialization since the repeated calls to poll() do not create a fresh object for d but merely update the response field with a new r.data object.

$scope.data -> d.response -> r.data

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

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Navigating a variety of page styles and views in Angular 1 using routing

Following a tutorial, I have set up code that routes to various pages related to the main type of document used in the application: angular.module('loc8rApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']); function ...

Interacting with a third-party application via OAuth using Node server to send REST requests

https://i.stack.imgur.com/Znrp0.png I've been working on a server to manage chat messages and need to integrate with a JIRA instance. I'm currently using the passport-atlassian-oauth strategy for authentication and BearerStrategy for requests. H ...

Increasing the size of a background image as you scroll

Is there a way to adjust the background image of a div so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image ...

Press and hold feature using CSS or JavaScript

When working with a jQuery draggable element, my objective is to change the cursor to a move cursor when clicking and holding the header. I have attempted using CSS active and focus properties, but so far no changes are taking place. ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Validating AngularJS form upon submission

In my AngularJS application, I am looking to incorporate a form validation that only displays errors after the user clicks the submit button. I want to avoid real-time validation as I type or upon exiting the field. Is there a method to achieve this? I an ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Is there a way to handle the ajax request only when necessary, instead of processing it every few seconds?

Currently, I am working on an AJAX chat system using PHP, MySQL, JavaScript, and AJAX. I have a piece of code that retrieves all chat messages within a div using AJAX, with the function running every 2 seconds. My issue lies in the fact that the div autom ...

Having some trouble creating a ping command in discord.js that displays latency; encountered this error message

I encountered an issue while trying to create a ping command that displays latency. I am unsure why this error is showing up, here is the specific error message - TypeError: Cannot read properties of undefined (reading 'ping') at Object.execu ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Create a dynamic animation page using Node.js, then seamlessly redirect users to the homepage for a smooth user

Good day everyone! I've decided to change things up with my latest query. I'm currently working on adding a loading page animation that will show for 3 seconds when visiting the '/' route, and then automatically redirect to the home pag ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

Yet another error encountered: "Headers cannot be set after they have already been sent to the client" when submitting the form

Whenever I try to submit text to a single-field form on my node.js server, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Iterate over each option in a select dropdown menu and modify them

Below is the test code snippet I am working with: ID = { CreatedBy: { id: 'createdBy' }, ModifiedBy: { id: 'modifiedBy' } } Profile = { All: { text: 'All', val: 0 }, Sys: { text: '<a href="/cdn-cgi/l/emai ...

Guide to displaying a pop-up modal containing text and an image when clicking on a thumbnail image

Recently delving into Bootstrap 3, I created a thumbnail grid showcasing images related to various projects. My goal is to have a modal window pop up when clicking on an image. Within the modal, I want to display the selected image alongside some descrip ...