2016-11-03 24 views
0

我有一個窗體和它上面的顯示字段。我只想在提交後更新顯示值。這適用於第一次提交。直到我提交它,值不會改變,並且一旦我點擊收集它更新值,然後,似乎ng-model以某種方式綁定並保持綁定到上方對象,因爲當我繼續鍵入輸入字段上的值更新自動。對我來說這是一個奇怪的行爲,我希望他們只有在我提交之後才能更新。有任何想法嗎?角度ng模型更新提交後的父對象並保持有界

這裏是代碼:

function Ctrl($scope) { 
 
    $scope.customFields = ["Age", "Weight", "Ethnicity"]; 
 
    $scope.person = { 
 
     customfields: { 
 
      "Age": 0, 
 
       "Weight": 0, 
 
       "Ethnicity": 0 
 
     } 
 
    }; 
 
    $scope.submited = { 
 
    \t "person" : { 
 
     \t  "customfields" : { 
 
     \t  "Age" : 0, 
 
       "Weight" : 0, 
 
       "Ethnicity" : 0 
 
      } 
 
     } 
 
    }; 
 

 
    $scope.collectData = function() { 
 
     $scope.submited.person.customfields = $scope.person.customfields; 
 
     console.log($scope.person.customfields); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app ng-controller="Ctrl"> 
 
    <div ng-repeat="fields in submited.person.customfields"> 
 
    {{fields}} 
 
    </div> 
 
    <div class="control-group" ng-repeat="field in customFields"> 
 
     <label class="control-label">{{field}}</label> 
 
     <div class="controls"> 
 
      <input type="text" ng-model="person.customfields[field]" /> 
 
     </div> 
 
    </div> 
 
    <button ng-click="collectData()">Collect</button> 
 
</div>

回答

0

當您使用:

$scope.submited.person.customfields = $scope.person.customfields; 

變量變成彼此的克隆 - 它是JS中的一個屬性。因此,當您使用該對象進行綁定時,值保持綁定狀態。你基本上只是爲已經存在的對象創建另一個參考。

angular.copy僅將對象的結構和數據複製到另一個上。因此,發生克隆而不是創建對象的引用。

因此,將其更改爲:

$scope.submited.person.customfields = angular.copy($scope.person.customfields); 
+0

感謝您的解釋,這解決了問題! – bigcat

1

改變這一行

$scope.submited.person.customfields = $scope.person.customfields; 

$scope.submited.person.customfields = angular.copy($scope.person.customfields);