Ajith
Ajith

Reputation: 393

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[]
 }
    });

Upvotes: 3

Views: 139

Answers (5)

filype
filype

Reputation: 8380

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).

Upvotes: 1

Elo
Elo

Reputation: 2352

As you want to do it dynamically, I think you could use a "watch" :

$rootScope.$watch('variableToWatch', function() {
       // - Call concat code here
   });

Your code is then executed each time a source data is changed. Of course you have to add "$rootScope" dependency to your service.

Upvotes: 1

Azad
Azad

Reputation: 5264

use array concat

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    this.comonData = [];
    this.tabData = [];
    this.pushArray = function (arrayName) {
        this.comonData = this.comonData.concat(arrayName);
  }
});

Upvotes: 1

sdgluck
sdgluck

Reputation: 27257

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.

Upvotes: 1

Clay
Clay

Reputation: 4760

You can merge an array using concat:

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
// Result is: Cecilie,Lone,Emil,Tobias,Linus

In your case:

this.comonData.concat(someOtherArray);

Upvotes: 0

Related Questions