前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >AngularJS API之copy深拷贝

AngularJS API之copy深拷贝

作者头像
用户1154259
发布2018-01-17 16:39:03
5880
发布2018-01-17 16:39:03
举报

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

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

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

下面看看使用样例:

代码语言:javascript
复制
<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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-11-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用时需要注意下面几点:
  • 下面看看使用样例:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档