2016-03-05 48 views
1

我有加載時發送GET請求,其將存儲在「主」服務器和收到
數據的形式,我複製如下數據,以「本地」。對象比較在AngularJS

$scope.dirty = false; 

init(data); 

function init(data) { 
    $scope.master = angular.copy(data.data); 
    $scope.local = angular.copy($scope.master); 
} 

現在,我使用本地對象作爲我的窗體的模型,我必須按鈕提交和重置。我看下面的本地對象。

$scope.$watchCollection('local', function (newLocal, oldLocal) { 
    $scope.dirty = !angular.equals(newLocal, $scope.master); 
}); 

因此,如果髒了是真的話,我可以知道數據已被修改,但因爲我使用的對象AngularJS增加$$ hasKey到$scope.local和因爲$scope.dirty總是設置爲true。

那麼,有沒有什麼辦法來處理這個問題?我是AngularJS的新手,可能這可能是一個有趣的問題,但我被卡住了。

回答

0

我發送數據的形式PHP和PHP把數字和字符串作爲單獨的數據類型。 因此,我將這些Number數據轉換爲字符串,現在它可以按照需要工作,並且我會說,只要我使用<form name='newForm> angularJS創建一個名爲newForm的新scope,以便我可以爲您的許多屬性範圍如$dirty, $pristinem $submitted and many more.所以現在我不必寫這個邏輯通過自己

1

你可以比較convert your objectJSON字符串之前:

function init(data) { 
    // store json data into $scope.master for later comparison 
    $scope.master = angular.toJson(data.data); 
    $scope.local = angular.copy(data.data); 
} 

$scope.$watchCollection('local', function (newLocal, oldLocal) { 
    var json = angular.toJson(newLocal); // new local without $$ key 
    $scope.status.dirty = !angular.equals(json, $scope.master); 
    // $scope.local is still a javascript object 
}); 
+0

如果我用這個代碼,然後$ scope.local = angular.copy($ scope.local)不會工作。所以,我必須使用$ scope.local = angular.copy(data.data)對不對? – nextt1

+0

怎麼樣?那麼你可以引入另一個變量? – cl3m

+0

以上代碼不起作用。 – nextt1