I am referring to this code on form posting as coresponding to angular documentation on simple form.
What is the use of angular.copy over here? it seems that the code still working fine in the case where angular.copy being removed.
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
答案 0 :(得分:0)
angular.copy() to make a deep copy of the contact object. The reason for this is that user is being overwritten ( you can see by using debugger point ).
As can be read here angular.copy() performs a deep copy (cf. "clone") of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.
Thus in the latter case, if you we're to change something in $scope.master you would also change context.