Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new array in to existing array dynamically

I want add new array in existing array dynamically. Here I am try to add array to the existing array in a shared service.

here is my code

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    this.comonData = [];
    this.tabData = [];
    this.pushArray = function (arrayName) {
        //this.comonData.push(arrayName[]);
          // here i want to add commonData.newArray[]
 }
    });
like image 601
Ajith Avatar asked Dec 13 '25 14:12

Ajith


2 Answers

You need to store the value of this in a variable before referencing it within a nested function.

For example:

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    var self = this;
    this.comonData = {};
    this.tabData = [];
    this.pushArray = function (key, value) {
        // self holds the value of the parent instance
        self.comonData[key] = value;

}});

self is now being used to maintain a reference to the original this even as the context has changed (inside another function).

like image 127
filype Avatar answered Dec 15 '25 02:12

filype


Use Array#concat:

this.comonData = this.comonData.concat(arrayName);

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

like image 33
sdgluck Avatar answered Dec 15 '25 02:12

sdgluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!