Populate an empty object by listening for an event in AngularJS

Using my service, I trigger the event using $rootScope.$emit. In the controller, I listen for this event and store the passed data in an array. This allows me to display the values using the ng-repeat directive.

When the service function is called, it adds two new values to the array in the controller. While this approach worked well initially, I now need to display the data in multiple locations, so I want to store it as an array object instead of a simple array. However, I am facing difficulties in creating an empty array object in JavaScript that can be extended with each emit event.

An example schema of the empty array object could look like:

arrayObject = [
    {
        firstValue: value,
        secondValue: value
    }
];

I would like to add data to this object in the controller when the event is triggered. Currently, the code that stores data in a simple array looks like this:

$rootScope.$on('colorChanged', function(event, data) {
  console.log('colorChanged event emitted');
  console.log(data);
  if(data) {
      vm.convertedColors.push(data);
  }
});

The data being passed is a string from the service.

Each time functions are executed from the service, an event is emitted twice - once after the completion of the first method with `firstValue`, and then again after the second method with `secondValue`. Working with an object array instead of a simple array would make this process much cleaner.

Is this feasible?

EDIT

Even though I pass values like {colorInHEX: "#ff0000"} and {colorInHSL: "hsl(0, 1%, 0.5%)"} to the $on function, I encounter an error:

TypeError: Cannot read property 'firstValue' of undefined

vm.convertedColors = [];

$rootScope.$on('colorChanged', function(event, data) {
    console.log('colorChanged event emitted');
    console.log('colors in others: (in controller)' + data);
    console.log(data);
        lastObj = vm.convertedColors[vm.convertedColors.length - 1];
        if (!lastObj.firstValue || !lastObj.secondValue) {
            vm.convertedColors[vm.convertedColors.length - 1] = Object.assign(lastObj, data);
        } else {
            vm.convertedColors.push({});  
        }
    }
});

$rootScope.$emit('colorChanged', {colorInHSL});
$rootScope.$emit('colorChanged', {colorInHEX});

EDIT2

This issue seems to be related to replacing existing data rather than adding new entries. I have created a demo on Plunker to illustrate the problem. The data in this demo is hardcoded, but clicking the button should create a new <li> element with the same value.

Link to plunker: link

Answer №1

To handle values for firstValue and secondValue properties, Object.assign can be utilized in cases where ECMAScript6 is compatible:

// Implementation in controller:
vm.convertedColors = [{}];

$rootScope.$on('colorChanged', function(event, data) {
    if(data) {
        var lastObj = vm.convertedColors[vm.convertedColors.length - 1];
        if (!lastObj.colorInHSL || !lastObj.colorInHex) {
            vm.convertedColors[vm.convertedColors.length - 1] = Object.assign(lastObj, data);
        } else {
            vm.convertedColors.push(Object.assign({}, data)); // Add a new object
        }
        $timeout(function() {}); // Trigger a new $digest cycle to update the view.
        console.log("Array: ", vm.convertedColors);
    }
});

// Triggering in service:

var colorInHSL = 'hsl(' + 1 + ', ' + 100 + '%, ' + 100 + '%)';
$rootScope.$emit('colorChanged', {colorInHSL: colorInHSL});
setTimeout(function() {
    $rootScope.$emit('colorChanged', {colorInHex: "#ff0000"});  
}, 3000); // Wait 3 seconds before emitting the second value (for observation)

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

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

Python + OOP: Implementing attributes and initializing a Game Object

Hey there, I'm looking to confirm if my implementation of adding the sword and axe to my objects is correct. In my game, I want my character to move forward by +2 when attacking and backward by -2 when defending. Can you review my 'move' cod ...

Tips for ensuring the correct page loads when using the back button in your browser

On my webpage, there is a search bar that displays search results in a resultdiv when I type something. However, if I navigate to another page and return by clicking the back button, the resultdiv no longer shows my previous search results. I would like ...

"JavaScript: Issue Encountered While Converting Hexadecimal to Decimal

I've been working on a custom function to convert hexadecimal to decimal in my Scratch project: function Hex2Decimal(hex){ var deci = 0; var num = 1; var hexstr = String(hex); hexstr = hexstr.toLowerCase(); var expon = 0; for( ...

Looking to resolve an issue that is arising in the antd tree component

Having trouble with the antd tree component - when searching and checking/unchecking a field, all previously selected data is unchecked. I want to only update the field that is currently being changed. Not sure how to fix this issue, any help would be appr ...

Establishing verification of a client-side application to a REST API through CORS using a local strategy

The Challenge: Providing a secure API for a client-side application using only local authentication methods. The missing piece of the puzzle is represented by the red arrows. Situation: In this scenario, client.example.com sends a POST request to a ...

When visiting this website, a special feature is enabled where the page will automatically refresh every 5 seconds. As the countdown begins, the numbers 5, 4,

Could use some assistance with setting up an HTML page to reload every 5 seconds and display a countdown when the refresh link is clicked. After clicking the refresh link, it should disappear and show a countdown from 5 to 1 before reloading the page aga ...

Tips on integrating a series of typical utility directives into an Angular module

If we have a collection of versatile angular directives, such as one that ignores non-numeric characters when typed, how can we best organize and include them in our Angular modules? Should we create a separate module, like Foo, to house these directives? ...

CSS: Strategies for eliminating empty cells within a grid layout by filtering out rows that contain partial or incomplete content

I am in need of creating a grid layout where each div is a specific width, and the number of rows depends on how many items there are. The twist is that I am unsure of the width of the outer container. My initial solution was to use CSS grid: #container ...

Is ngwebdriver compatible with Appium for testing iOS applications?

Our team is currently working on a Cordova angular mobile app and looking to implement automation testing. Since we are not well-versed in javascript, we prefer not to use the protractor tool. Is it possible to utilize ngWebDriver with appium and seleniu ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

Summing up the even values in an array using a For-loop in C# programming

I need to create an array and only add the even numbers in it using a for loop. I have set up the array but am not sure how to implement it in the loop. It seems like I should use the % operator to filter out the even numbers in the array. Although I am ...

The model I exported from Clara.io is not showing up on the Three.JS canvas, only a black square is

I recently started using Three.JS and imported an object I exported as a JSON from clara.io. Unfortunately, the object is not appearing in the canvas, instead I see a black square with the dimensions I specified in the variable (400 by 300 pixels). Below ...

React has reached the maximum update depth limit

In my current project, I am developing a react application that involves a user inputting a search term and receiving an array of JSON data from the backend. On the results page, I have been working on implementing faceted search, which includes several fi ...

Sending emails to multiple recipients with different content using Nodemailer

I have been working on a method to send emails to multiple recipients while also passing the user attribute, which contains the name of the recipient, to the html template. (I AM UTILIZING NODEMAILER as a nodejs module) My current code looks like this: S ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

The Angular state provider will consistently land on the 'otherwise' state

I am facing an issue with setting the state through a controller while parsing only 1 parameter. It seems like the preferred state is called, but then the "otherwise" state is loaded right after. Interestingly, I noticed that the preferred state was being ...

What are the steps to successfully install the movie-trailer npm package while avoiding any potential errors?

Is there a way to successfully install the movie-trailer npm package without encountering these issues? $ npm I movie-trailer npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code E404 npm ERR! 404 No ...