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