简体   繁体   中英

AngularJs pushing multiple values from array to another with databinding refreshing

I am getting an array from the server which can contain 0..n elements in an array. I then add that to array I use locally for databinding (basically cache data in client). When doing it this way databiding works without any problems:

for (var i = 0 ; i < data.Result.length ; i++) {
    scope.cachedData.push(data.Result[i]);
}

Meaning - view refreshes, everything works. But when I try: scope.cachedData.concat(data.Result); it won't work. Why is that?

If you want to push everything in a single instruction use apply without breaking the reference to scope.cachedData

Array.prototype.push.apply(scope.cachedData, data.Result);

Also, I know this is a little bit off topic but if you want to insert at a specific index you can use splice with apply

// I definitely want to prepend to my array here
var insertionIndex = 0,
// we don't want to delete any elements here from insertionIndex
    deleteCount = 0;
// Because we use apply the second argument is an array
// and because splice signature is (startIndex, noOfElementsToDelete, elementsToInsert)
// we need to build it
Array.prototype.splice.apply(scope.cachedData, [insertionIndex, deleteCount].concat(data.Result));

Imagine your array scope.cachedData = [3,4]; and data.Result = [1,2]; , with the code above scope.cachedData will become [1,2,3,4] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM