Angularjs: assign $.resource data to $scope
Blogs20142014-06-21
Angularjs: $.resource return data
In Angularjs, data returned from $.resource seems can’t assign to a $scope property. The returned data is not a standard Array, so some weired result:
`//The returned data is a 'Resource' object, here is a fake:var data=[{‘a’:1}, {‘b’:2}, {‘x’:‘xyz’}, {m:123}]; //then: //1. concat() not work: $scope.ary = ($scope.ary || ($scope.ary=[])).concat(data); //2. slice.call() not work: $scope.ary=(Array.isArray($scope.ary)||($scope.ary=[])).slice.call(data); //3. directly assign the reference will work: $scope.ary = data; //4. [].push also works: for (var i in data) { $scope.ary[i] = data[i]; }`
According to w3schools.com, The concat() method is used to join two or more arrays: array1.concat(array2, array3,…, arrayX). This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays. So why not work? I changed to the following, and it works fine:
if($scope.members.length===0) {
$scope.members = data;
}
else {
for (var x in data) {
if(/d/.test(x) && data[x])
$scope.members.push(data[x]);
}
}Here is a helpful tip from stackoverflow:
`//1. not workvar o={0:“a”, 1:“asdf”} Array.prototype.slice.call(o,1) //[] Array.prototype.slice.call(o) //[]
//2. o is not an array-like object - it has no length property. //add a ‘length’ property to it will work var o={0:“a”, 1:“asdf”, length:2}; [].slice.call(o, 0); //[“a”, “asdf”] [].slice.call(o, 0,1) //[‘a’] [].slice.apply(o, [0,2]) //[“a”, “asdf”]`
