AngularJS API之copy深拷贝

angular提供了一个可以复制对象的api——copy(source,destination),它会对source对象执行深拷贝。

使用时需要注意下面几点:

  • 如果只有一个参数(没有指定拷贝的对象),则返回一个拷贝对象
  • 如果指定了destination,则会深拷贝对象复制给destination
  • 如果source是null或者undefined,那么会直接返回source
  • 如果source就是desitination,那么会报错。

下面看看使用样例:

<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="copyExample">
 <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)">SAVE</button>
        </form>
 <pre>form = {{user | json}}</pre>
        <pre>master = {{master | json}}</pre>
 </div>

    <script>
    angular.module('copyExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
        $scope.master= {};
        
        var test1;
        console.log(angular.copy(test1));//undefined
        var test3=null;
        console.log(angular.copy(test2));//undefined

        var test2 = "a";
        // console.log(angular.copy(test2,test2));//error!!

        $scope.update = function(user) {
           // Example with 1 argument
           $scope.master= angular.copy(user);
        };

        $scope.reset = function() {
            // Example with 2 arguments
            angular.copy($scope.master, $scope.user);
            console.log($scope.master);
            console.log($scope.user);
        };

       $scope.reset();
    }]);
    </script>
</body>
</html>

转载于:https://my.oschina.net/u/204616/blog/545220

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值