2015-12-29 143 views
3

我想在现有阵列中动态添加新阵列。这里我尝试将数组添加到共享服务中的现有数组中。如何将新阵列动态添加到现有阵列中

这里是我的代码

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

回答

1

在嵌套function中引用它之前,您需要将this的值存储在变量中。

例如:

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现在被用来维护到原始this基准甚至作为上下文已经改变(另一个函数内)。

+0

谢谢,它在arrayName [] – Ajith

+0

右边显示一些语法错误,移除'[]'使它变成'self.comonData.push(arrayName);' – Filype

+0

Filype,我把数组名称设置为“new”,但是icant访问this.comonData.new。 – Ajith

0

可以使用CONCAT合并数组:

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

你的情况:

this.comonData.concat(someOtherArray); 
1

使用Array#concat

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

concat()方法返回一个新的数组,该数组由一个数组组成,在该数组上调用它与作为参数提供的数组和/或值连接。

1

使用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); 
    } 
}); 
+0

谢谢azzi,这包括[“arrayName”],我想访问像this.commonData.newArray这样的新数组 – Ajith

1

至于要动态做到这一点,我想你可以使用一个“看”:

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

你的代码是每一个源数据改变时,则执行。 当然,您必须将“$ rootScope”依赖项添加到您的服务中。

+0

Elo,你可以在这里粘贴一个例子吗? – Ajith

+0

我认为concat方法本身已被其他答案很好地描述。最终代码取决于您接收要添加到数组中的数据的方式(Ajax调用?)。此外,我不确定我是否正确理解了您的最终需求,但只要您“动态”提及,我认为使用$ watch的观察员可以提供帮助。 – Elo