当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS API之copy深拷贝详解及实例

AngularJS API之copy深拷贝详解及实例

2018年05月10日  | 移动技术网IT编程  | 我要评论

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

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

  1. 如果只有一个参数(没有指定拷贝的对象),则返回一个拷贝对象
  2. 如果指定了destination,则会深拷贝对象复制给destination
  3. 如果source是null或者undefined,那么会直接返回source
  4. 如果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>




以上就是对angularjs api之copy深拷贝的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网