对angular.extend的调用不会导致$ scope。$ watch to proc

时间:2013-11-08 15:16:04

标签: javascript angularjs coffeescript

我正在使用angular.extend将较小的对象合并为更大的对象。

以下是数据样本:

$scope.bigDocument = {
    "id": 0,
    "guid": "e75ce3b3-68f6-423f-94d8-1a613cde0c59",
    "isActive": true,
    "balance": "$2,437.00",
    "picture": "http://placehold.it/32x32",
    "age": 38,
    "name": "Parks Williamson",
    "gender": "male",
    "company": "Arctiq",
    "email": "parkswilliamson@arctiq.com",
    "phone": "+1 (817) 488-3119",
    "address": "252 Concord Street, Morgandale, Arizona, 1866",
    "about": "Irure nostrud nisi qui do amet nisi adipisicing dolor eiusmod do non laboris.",
    "registered": "1995-04-08T20:16:47 +05:00",
    "latitude": -6.796341,
    "longitude": 40.321499,
    "randomArrayItem": "cherry"
}

$scope.littleDocument = {
     "balance": "$3,193.00",
     "picture": "http://placehold.it/32x32",
     "age": 22, 
     "name": "Coffey Wilcox",
     "gender": "male",
     "company": "Balooba",
     "email": "coffeywilcox@balooba.com",
     "phone": "+1 (824) 518-3639",
     "address": "836 Douglass Street, Imperial, Montana, 9365",
     "about": "Ipsum dolore officia consectetur proident occaecat.",
     "registered": "1994-12-12T15:47:09 +06:00",
     "latitude": -33.474425,
     "longitude": -113.998081,
}

我正在使用以下功能进行合并:

$scope.merge = function() {
    angular.extend($scope.bigDocument, $scope.littleDocument)

并通过以下

观看更改
$scope.$watch('bigDocument', function(newVal, oldVal) {
    console.log('bigDocument Changed');
})

我在$ scope.bigDocument的初始水合作用下得到了预期的输出,但是在调用合并函数之后却没有。数据更改正确,但$ watch方法永远不会受到影响。

是什么给出了?

这是一个用于显示完整工作流程的plunker(在coffeescript中):http://plnkr.co/edit/VPnxhUa6uz1zKfcufb2J

1 个答案:

答案 0 :(得分:5)

$ watch函数接受third boolean parameter,表示要比较对象的相等性或参考:

$scope.$watch('bigDocument', function(newVal, oldVal) {
    console.log('bigDocument Changed');
}, true);

plunker按预期工作。