關於angular.extend的用法


ng中的ng-function中會有些方法,便於我們進行js代碼的編寫

關於angular.extend(dst, src);通過從src對象復制所有屬性到dst來擴展目標對象dst。你可以指定多個src對象。

注意:angular.extend(....)只是簡單的對象之間的相互引用,

 

經典的demo ;

<!DOCTYPE html>
<html ng-app="extendApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
</head>
<body>

<div ng-controller="extendController">

<button ng-click="extend()">點擊我!</button>

</div>
</body>
</html>

<script type="text/javascript">
angular.module("extendApp", [])
.controller("extendController", function($scope)
{
$scope.baby =
{
cry : function()
{
console.log("I can only cry!");
}
}

$scope.adult =
{
earn : function()
{
console.log("I can earn money!");
},
lover:
{
love:function()
{
console.log("I love you!");
}
}
}
$scope.human = {}

$scope.hehe = "hehe ";

$scope.extend = function()
{
angular.extend($scope.human, $scope.baby, $scope.adult);
$scope.human.cry();
$scope.human.earn();
// $scope.human 和$scope.adult其實引用的是同一個對象-
$scope.human.lover.love = function()
{
console.log("I hate you!");
}

//這兩行都會輸出“I hate you !",可憐的adult對象, 他把自己的lover分享給了human! -->
$scope.human.lover.love();
$scope.adult.lover.love();
}
});
</script>

結果:

  I can only cry!
  I can earn money!
  I hate you!
  I hate you!

 

 

拓展:關於對象,數組的復制,我們可以進一步的了解angular.copy();的使用方法


免責聲明!

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



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