AngularJS方法 —— angular.copy


描述:

  復制一個對象或者一個數組(好吧,萬物皆對象,數組也是一個對象)。
  如果省略了destination,一個新的對象或數組將會被創建出來;
  如果提供了destination,則source對象中的所有元素和屬性都會被復制到destination中;
  如果source不是對象或數組(例如是null或undefined), 則返回source;
  如果source和destination類型不一致,則會拋出異常。
  注意:這個是單純復制覆蓋,不是類似繼承

 

使用方法:

  angular.copy(source, [destination]);

 

參數:

參數名稱 參數類型 描述
source * 被copy的對象. 可以使任意類型, 包括null和undefined.
destination (optional) Object||array copy去的目的地. 可以省略, 如果不省略, 其必須和source是同類

 

返回值:

  返回復制或更新后的對象。

 

實例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="js/angular.min.js"></script>
        <script type="text/javascript">
            angular.module('copyExample', []).controller('ExampleController', ['$scope', function ($scope) {
            $scope.master = {};
            $scope.update = function (user) {
                //將user復制后,賦值給master;
                    $scope.master = angular.copy(user);
            };
            
            $scope.reset = function () {
                // 將復制后的$scope.master,賦值給$scope.user,因為$scope.master = {},所以點擊RESET,會清空郵箱內容
                angular.copy($scope.master, $scope.user);
            };
            $scope.reset();
            }]);
        </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" />(輸入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>
</body>
</html>

 

點擊sava按鈕之前效果:

 

點擊sava按鈕之后的效果:

 

點擊reset之后的效果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM