Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource.

Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones.

The JSON message I receive:

[
{"age": 0,"id": "my first tweet","name": "Hello Sarah","snippet": "It's fabulous"},
{"age": 1,"id": "my second tweet","name": "Hello dude !","snippet": "It's fabulous"}
]

My Service :

'use strict';

/* Services */

var listlogServices = angular.module('listlogServices', ['ngResource']);

listlogServices.factory('Log', ['$resource',
  function($resource){
    return $resource('log/log1.json', {}, {
      query: {method:'GET', params:{}, isArray:true}
    });
  }]);

My controller and functions

'use strict';

var app = angular.module('appRecupTweetApp');


app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){

  $scope.$watch(function () { return Timer.data.myTab; },
    function (value) {
      $scope.data = value ;
      //$scope.data.push(value);
      //$scope.data = $scope.data.concat(value);
    }
  );

});

app.service('Timer', function ($timeout, Log) {

  var data = { myTab: new Array()};

  var updateTimer = function () {
    data.myTab = Log.query();
    $timeout(updateTimer, 5000);
  };

  updateTimer();

  return {
    data: data
  };
});

I attempted to merge my object using 'push' and 'concat' methods but faced an issue. Corrected error (Angular says : $scope.data is undefined )

Should I perform this operation in my 'Timer' service or in my controller, and what would be the best solution?

Online demo : plnkr.co/edit/Vzdy9f7zUObd71Lm86Si

Thank you

Guillaume

Answer №1

Initializing the $scope.data variable within your TimerCtrl1 controller is crucial.

 app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){
$scope.data=[];
  $scope.$watch(function () { return Timer.data.myTab; },
    function (value) {
      $scope.data = value ;
      //$scope.data.push(value);
      //$scope.data = $scope.data.concat(value);
    }
  );

});

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

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

Ionic state is malfunctioning

I'm facing an issue with the state (I'm having trouble grasping how it functions). Here's a snippet of my app.js code: .... app.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) { // $ionicConfigProvider.views.trans ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Adding objects to an existing array in Vue.js can be a seamless and

Struggling to populate my existing array with elements from a JSON response using a button click. The issue lies in properly adding these elements to the array. I have an empty array named results where I store the data from the response. export default ...

Retrieve the nearest attribute from a radio button when using JQuery on a click event

I have a query regarding the usage of JS / JQuery to extract the data-product-name from a selected radio button, prior to any form submission. Although my attempt at code implementation seems incorrect: return jQuery({{Click Element}}).closest("form" ...

Customizing Pie Legends in Echart Configuration

I am trying to find a way to present pie chart legends along with their values in a unique format. I have attached an image for reference. Despite my efforts, I haven't been able to figure out how to achieve this specific display. If you take a look a ...

How to adjust transparency in Three.js objects

Currently, I am developing a scene where certain elements are loaded from a JSON file. While I am able to toggle the visibility of each individual object, I now find myself wanting to adjust the opacity/transparency of an individual object. The objects in ...

Creating a React component dynamically and applying unique custom properties

I'm currently in the process of refactoring my React code to enhance its usability in situations where direct use of Babel is not possible, such as in short snippets of JavaScript embedded on web pages. As part of this refactor, I am setting up a conc ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

"An issue with jquery.maxlength.js arises when attempting to apply it to a textarea within a populated table in Angular

In my current project, I am utilizing the jquery.maxlength.js (version 1.0.5) plugin to handle textareas in a single page application built with AngularJS (version 1). Everything is working smoothly for textareas outside of tables, but I am facing an issue ...

How can I retrieve the value of a <span> element for a MySQL star rating system?

Source: GitHub Dobtco starrr JS plugin Implementing this plugin to allow users to evaluate a company in various categories and store the feedback in a MySQL database. Enhancement: I have customized the javascript file to enable the use of star ratings fo ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Achieve resumable uploads effortlessly with google-cloud-node

While this code works well for regular uploads, I am curious about how the resumable upload feature functions when a user loses connection during a large upload. Does simply setting 'resumable' to true in the writeStream options make it work effe ...

How can I retrieve the values of jQuery select2 tag list in ASP.NET?

I am looking to retrieve the selected values from the jQuery Select2 plugin in my ASP.NET code behind. Below is a snippet of my code: Client Side: <select id="ddlcountry" runat="server" class="select" style="width: 100%;"> ...

Script execution in '<URL>' has been prevented due to sandboxing of the document's frame and the absence of the 'allow-scripts' permission setting

When I deploy my pure Angular application with a REST API to a production server and try to access its URL from another site (such as a link in an email), I encounter a strange problem. Firefox doesn't provide any error message, but Chrome says: Blo ...

Calculating the sum of all elements in an array

Hi, I am currently attempting to retrieve the total value from an array (such as Arr[1] + Arr[2], and so forth). Unfortunately, I am struggling to find a solution. Below is my existing function: this.hourlyTotals = function() { var custsperhour = Math ...

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Uploading Images Dynamically with AJAX

Can someone assist me with a multiple upload form that utilizes AJAX to upload and display an image without the need for a submit button? My issue arises when dealing with repeating forms within table rows, causing only the first form to function properly. ...