【问题标题】:Why array in $scope doesn't updated using array concat method?为什么 $scope 中的数组不使用数组 concat 方法更新?
【发布时间】:2016-04-29 13:30:01
【问题描述】:

当我使用 concat 方法时,我的 $scope 没有更新

var anotherList = ["2", "3", "4"];
$scope.list     = [];

$scope.list.concat(anotherList);

但是在循环中使用数组推送方法,我的 $scope 得到了更新

【问题讨论】:

    标签: arrays angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    您的语法错误。您需要将 .concat() 的返回值分配给您的作用域数组。

    $scope.list = $scope.list.concat(anotherList);
    

    或者,如果您使用call(),您可以将结果直接绑定到作用域数组,而无需“重新分配”,因为它会在后台为您完成。

    $scope.list.concat.call(anotherList);
    

    请参阅documentation

    【讨论】:

    • 谢谢 David L,我对 JavaScript 和 AngularJS 很陌生
    • @EricdosReis 没问题!如果您不知道自己在寻找什么,这很容易被忽略。
    【解决方案2】:

    大卫所说的是正确的。只是补充一点: concat() 不会修改数组,它只是根据接收到的参数返回一个新数组。检查此以获取更多信息:

    http://www.w3schools.com/jsref/jsref_concat_string.asp

    【讨论】:

      【解决方案3】:

      如果您想维护原始数组,而不是concat,您可以这样做:

      Array.prototype.push.apply($scope.list, anotherList);
      

      【讨论】:

        猜你喜欢
        • 2015-06-09
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-12
        • 1970-01-01
        相关资源
        最近更新 更多