【问题标题】:Angularjs: prevent bindingAngularjs:防止绑定
【发布时间】:2014-08-25 22:52:41
【问题描述】:

在这种情况下如何防止绑定:

$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
$scope.twoofthedata = [$scope.data, $scope.data];

因此 $scope.twoofthedata[0] 独立于 $scope.twoofthedata[1]

plunker

【问题讨论】:

    标签: angularjs binding


    【解决方案1】:

    在 JavaScript 中,对象被操纵by reference。这不是 Angular 绑定问题。

    不过,Angular 允许您通过 angular.copy 方法绕过此语言约束,该方法会创建给定对象的深层副本。

    $scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
    
    // Manually call `angular.copy` on each member
    $scope.twoofthedata = [
      angular.copy($scope.data),
      angular.copy($scope.data)
    ];
    
    // Cleaner version (using `Array.prototype.map`)
    $scope.twoofthedata = [$scope.data, $scope.data].map(angular.copy);
    

    但是应该警告您,深拷贝可能非常昂贵,因此只有在真正需要时才使用。

    仅供参考:如果您遇到类似问题但未使用 Angular,您可以使用 Lodash,它也有 deep clone method

    【讨论】:

    • $watch() 出现了一些问题,并更改了 angular.copy($scope.data) > $.extend(true, {}, $scope.data); 现在不显示 RangeError: Maximum call stack size exceeded
    • $watch 遇到了什么问题?
    • RangeError: 超出最大调用堆栈大小
    • 你使用$.extend也有同样的问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2011-11-12
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多