温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

浅谈angular.copy() 深拷贝

发布时间:2020-10-17 09:12:48 来源:脚本之家 阅读:128 作者:爱吃菠萝蜜的小透明 栏目:web开发

因为项目中需要拷贝,查阅angularjs API文档,发现对angular.copy() 的解释:

复制一个对象或者一个数组(好吧,万物皆对象,数组也是一个对象)。

1> 如果省略了destination,一个新的对象或数组将会被创建出来;
2> 如果提供了destination,则source对象中的所有元素和属性都会被复制到destination中;
3> 如果source不是对象或数组(例如是null或undefined), 则返回source;
4> 如果source和destination类型不一致,则会抛出异常。 注意:这个是单纯复制覆盖,不是类似继承。

使用方法:

angular.copy(source, [destination]);

参数:

参数名称 参数类型 描述
source * 被copy的对象. 可以使任意类型, 包括null和undefined.
destination (optional) Object,array copy去的目的地. 可以省略, 如果不省略, 其必须和source是同类

返回值:

返回复制或更新后的对象

<!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>

效果图

浅谈angular.copy() 深拷贝

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI