AngularJSAngularJS API之copy深拷贝

下边看看使用样例:

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

行使时索要留意上面几点:

  • 假如唯有3个参数(未有点名拷贝的靶子),则赶回一个正片对象
  • 一旦钦点了destination,则会深拷贝对象复制给destination
  • 只要source是null恐怕undefined,那么会一直回到source
  • AngularJS,如果source正是desitination,那么会报错。

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

相关文章