淺談angular.copy() 深拷貝
因?yàn)轫?xiàng)目中需要拷貝,查閱angularjs API文檔,發(fā)現(xiàn)對angular.copy() 的解釋:
復(fù)制一個(gè)對象或者一個(gè)數(shù)組(好吧,萬物皆對象,數(shù)組也是一個(gè)對象)。
1> 如果省略了destination,一個(gè)新的對象或數(shù)組將會(huì)被創(chuàng)建出來;
2> 如果提供了destination,則source對象中的所有元素和屬性都會(huì)被復(fù)制到destination中;
3> 如果source不是對象或數(shù)組(例如是null或undefined), 則返回source;
4> 如果source和destination類型不一致,則會(huì)拋出異常。 注意:這個(gè)是單純復(fù)制覆蓋,不是類似繼承。
使用方法:
angular.copy(source, [destination]);
參數(shù):
| 參數(shù)名稱 | 參數(shù)類型 | 描述 |
|---|---|---|
| source | * | 被copy的對象. 可以使任意類型, 包括null和undefined. |
| destination (optional) | Object,array | copy去的目的地. 可以省略, 如果不省略, 其必須和source是同類 |
返回值:
返回復(fù)制或更新后的對象
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="copyApp">
<div ng-controller="CopyController">
<form novalidate class="simple-form">
姓名: <input type="text" ng-model="user.name" /><br />
年齡:<input type="number" ng-model="user.age" /><br />
郵箱: <input type="email" ng-model="user.email" /><br />
性別:<input type="radio" ng-model="user.gender" value="male" /> 男
<input type="radio" ng-model="user.gender" value="female" /> 女
<br />
<button ng-click="reset()">重置</button>
<button ng-click="update(user)">保存(拷貝)</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyApp', [])
.controller('CopyController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
console.log($scope.master);
};
$scope.reset = function() {
angular.copy($scope.user, $scope.master);
console.log($scope.master);// Object { }
console.log($scope.user); //undefined
};
$scope.reset();
}]);
</script>
</body>
</html>
效果圖

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS操作鍵值對象類似java的hashmap(填坑小結(jié))
我們知道java的hashmap中使用最多的是put(...),get(...)以及remove()方法,那么在angularJS中如何創(chuàng)造(使用)這樣一個(gè)對象呢?今天小編通過本文給大家分享下,感興趣的朋友一起學(xué)習(xí)吧2016-11-11
Angular中ng-repeat與ul li的多層嵌套重復(fù)問題
這篇文章主要介紹了Angular中ng-repeat與ul li的多層嵌套重復(fù)問題,需要的朋友可以參考下2017-07-07
Angular實(shí)現(xiàn)響應(yīng)式表單
本篇文章主要介紹了Angular實(shí)現(xiàn)響應(yīng)式表單,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
AngularJS實(shí)現(xiàn)注冊表單驗(yàn)證功能
這篇文章主要為大家詳細(xì)介紹了AngularJS實(shí)現(xiàn)注冊表單驗(yàn)證功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
angularjs實(shí)現(xiàn)與服務(wù)器交互分享
AngularJS是Google開發(fā)的純客戶端JavaScript技術(shù)的WEB框架,用于擴(kuò)展、增強(qiáng)HTML功能,它專為構(gòu)建強(qiáng)大的WEB應(yīng)用而設(shè)計(jì)。2014-06-06
Angular?結(jié)合?dygraphs?實(shí)現(xiàn)?annotation功能
這篇文章主要介紹了Angular?結(jié)合?dygraphs?實(shí)現(xiàn)?annotation,本文,我們直接結(jié)合 Angular 來演示,如何通過 dygraphs 實(shí)現(xiàn)折線圖上的 annotation 的功能,需要的朋友可以參考下2022-08-08

