Enhancing angular service with additional parameters

UPDATE: angular.extend and Object.assign both work fine, but which one is the better choice?

I am facing an issue where adding more values to an angularjs service variable overwrites the previous value. Here is a sample code snippet:

var testModule = angular.module('testmodule', [])

  .controller('abc', function ($scope, mser) 
 {
  mser.aa = {a:5, b:2};
  mser.aa = {c:5, d:2};
  $scope.inps = mser.aa.a
 })

 .service('mser', function() {
  var aa = {}
  return aa
  });

After executing mser.aa = {c:5, d:2};, the value of mser.aa.a becomes undefined. What can be done to prevent this and insert all values successfully?

Answer №1

By replacing the value of "mser.aa" with {c:5, d:2}, you are essentially updating the object. To expand on this action:

mser.aa = Object.assign(mser.aa, {c:5, d:2}); 

If you prefer utilizing angular techniques over basic javascript Object approaches, you can achieve the same result using the following method:

angular.extend(mser.aa, {c:6, d:7});

Answer №2

If you want to add properties to an object without overwriting existing ones, you can use the angulr.extend method like this:

myObj.animals = {dog:4, cat:6};
angular.extend(myObj.animals, {horse:2, rabbit:3});

By using this approach, the current object will be extended with the specified values instead of being overwritten.

Answer №3

Why not try using angular.extend() this time?

angular.extend(mser.ab, {e:9,f:3})

Answer №4

Here is an example of how you can set up your controller:

 .controller('xyz', function ($scope, service) 
 {
  service.data = {x:10, y:7};
  service.data.z = 10;
  service.data.w = 7;
  $scope.inputs = service.data.x  
})

Answer №5

mser.aa in JavaScript behaves as a regular property, meaning that when you assign an object to it, the existing one will be overridden. The correct approach is to modify the current object rather than replacing it entirely. Here's how you can achieve that:

mser.aa.a = 5;
mser.aa.b = 2;
mser.aa.c = 5;
mser.aa.d = 2;

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

Is there a specific regex pattern available to identify CSS and JavaScript links within an HTML file?

Currently, I am using a straightforward gulp task to compress my CSS and JS files. The task appends a .min extension to the names of the compacted files. Now, I want to make changes in the HTML to direct to these new compressed files, like so: Replace thi ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the p ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this: @WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true) public class CreateCon extends ...

Filtering data in AngularJS controller file allows you to easily manipulate and

Searching for a solution in the following function where the 'data' element contains multiple record sets. My goal is to filter it so that only the row with an id matching 'selectedModelDrv' is returned. I've attempted this but ke ...

Using AngularJS to Retrieve Data via a Factory

While I have come across multiple posts on this topic, I am struggling to adapt them to suit my specific requirements. A GET request is currently being made to a server in order to obtain a JSON response, and it functions perfectly. .controller('Lis ...

Using jQuery to create a checkbox that functions like a radio button

In my code, I have a bunch of checkbox elements placed in different containers as demonstrated below: $("input:checkbox").click(function() { var url = "http://example.com/results?&" var flag = false; var $box = $(this); var $facet = $box.val ...

Issue: [Fatal Error] AngularJS v1.7 and Jasmine

controller.js var testApp = angular.module('testApp', ['testModule']); angular.module('testModule') .component('testModule', { template: '<p> some things will be here</p>', ...

The NUXT project encounters issues when trying to compile

I am currently working on an admin panel using the nuxt + nest stack. I am utilizing a template provided at this link: https://github.com/stephsalou/nuxt-nest-template While in development mode, the project starts up without any issues. However, when I ...

Issue: Configuration Error - CKEditor5 cannot be loaded for extension in Vuejs

Hey everyone, I'm currently facing an issue. I'm trying to customize a build and everything works fine in the cloned ckeditor along with the sample.html file. However, when attempting to implement the customized build in Vue 2, I encounter an err ...

The page is having trouble loading images

My goal is to display sliding images in a web application using Bootstrap carousel. The images are fetched from the backend and stored in the 'images' state. Below is the JSON format of the data that is retrieved: images:[ { SNO:'1', NA ...

Displaying country-specific API details (such as capital and currency) in a card container when selecting a country from a dropdown menu

My objective is to display the card information for South Africa as the default value, even before entering any country's name into the search bar input field or selecting a specific country from the provided list. I am utilizing the restcountries API ...

Issue: ENOENT error occurred during execution on Docker Container due to missing file or directory '/root/.aws/credentials'

click here for image description While the app runs normally locally, attempting to run it in a Docker container results in an error displayed on the screen. This is my Docker file: FROM node:14.0.0 WORKDIR /app ARG DATABASE_URL ARG AWS_REGION ARG CLIENT_ ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

The initial state in NextJS fails to update when routing to the same page with different parameters

This particular project utilizes NextJS The structure of my page's URL is as follows: localhost:3000/first/second When I invoke getInitialProps on this page, the data retrieved from it is passed to the component and used to set the initial state li ...