AngularJS方法 —— angular.copy

來源:互聯網
上載者:User

標籤:json   content   res   rip   數組   radio   html   app   ted   

描述:

  複製一個對象或者一個數組(好吧,萬物皆對象,數組也是一個對象)。
  如果省略了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之後的效果:

 

 

AngularJS方法 —— angular.copy

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.