angular.copy
描述:
复制一个对象或者一个数组(好吧,万物皆对象,数组也是一个对象)。
如果省略了destination,一个新的对象或数组将会被创建出来;
如果提供了destination,则source对象中的所有元素和属性都会被复制到destination中;
如果source不是对象或数组(例如是null或undefined), 则返回source;
如果source和destination类型不一致,则会抛出异常。
使用方法:
angular.copy(source, [destination]);
参数详解:
Param | Type |
Details |
source | * |
被copy的对象. 可以使任意类型, 包括null和undefined. |
destination
(optional)
| ObjectArray |
copy去的目的地. 可以省略, 如果不省略, 其必须和source是同类型. |
返回值:
返回复制或更新后的对象
示例代码:
<!DOCTYPE HTML>
<html ng-app="copyExample">
<head>
<script src="angular.min.js"></script>
</head>
<body>
<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 />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">COPY</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.update = function(user) {
// 复制user对象给master
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// 复制user中的属性给master(首先会自动清除master中的属性)
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}]);
</script>
</body>
</html>