当前位置: 动力学知识库 > 问答 > 编程问答 >

AngularJS. I need compact way to merge custom scope with array of objects OR with single object

问题描述:

In my application I need to upload files and I try to implement the feature, that allow to add new files to files array instead of override it.

This is how I do it:

if (files) {

angular.forEach(files, function(file) {

$scope.files.push(file);

});

}

where files can be an array of File object or just single file.

Early I tried to push files to the scope as $scope.files.push(files), but as result I got array of nested arrays and can't processed it via ng-repeat.

I also tried $scope.files.concat(files), but as result I got empty array;

I also tried angular.extend($scope.files, files), but I got weird result:

when I add single file, it not pushed to the $scope.files but just replace $scope.files first element with itself. Same result if files contains more than one elements.

The question: does it exists more compact (and maybe faster) way to merge custom scope with array of objects or just one object?

Second question: why when I tried to angular.extend($scope.files, files), it not merged two arrays into one array, that contains elements of both, but just replace destination array with source?

网友答案:

Javascript's Array concat function returns a new array comprised of the arrays passed in. So you need to assign the result back to your scope variable:

if (files) {
  $scope.files = $scope.files.concat(files);
}
网友答案:

Check if files is an array or object, then either concat or push:

//null check and object check
if (files && typeof files === "object") {
    if (files.length) {
        $scope.files = $scope.files.concat(files); //array merge
    } else {
        $scope.files.push(files); //single obj
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: