現在比較火的前段JS框架像 VUE,REACK,ANGULAR,這三種框架都有共同的特點那就是,雙向數據綁定,組件化開發。而在angular1.5的版本之前,都是以directive作為組件化的形式,而directive本身是一個指令,而并非是一個組件,所以它并不能很好的承擔組件這一個職責,所以google在angular1.5的版本中推出了component組件,用于承擔應用之中組件化開發的重擔,那么component到底是如何工作的?又應該如何使用呢?我們將在這一章中詳細的探究一下component組件的使用方式。
在AngularJS中,Component比diective更適合于基于組件的開發形式。
先來看一個比較簡單的Component事例。
index.html
<!DOCTYPE html><html lang="en" ng-app="ComponentTestApp"><head> <meta charset="UTF-8"> <title>Document</title></head><body ng-controller="MainCtrl as ctrl"> <h3>hero</h3> <br> <hero-detail hero='ctrl.hero'></hero-detail> <script src="js/angular.js"></script> <script src="js/index.js"></script> <script src="js/heroDetail.js"></script></body></html>在index.html中我們定義了一個 hero-detail 標簽,這個標簽的聲明方式與 directive 相似 , 注意在這個標簽中定義了一個屬性 hero-detail , 這個定義的屬性是做什么用的那?我們接著往下看
index.js
(function(angular){ angular.module('ComponentTestApp',[]) .controller('MainCtrl',function(){ this.hero = { name:'Sunday' } });})(angular);在index.js中我們聲明了這個controller,并且在controller中我們寫了這么一行代碼
this.hero = { name:'Sunday' }相信細心的小伙伴已經看出來了,沒錯,這里對應我們在index.html中聲明的屬性 hero='ctrl.hero'
是component中通信的關鍵。
heroDetail.html
<h1>HeroName: {{$ctrl.hero.name}}</h1>在 heroDetail.html 中我們把從index.html中傳輸過來的值展示出來。
heroDetail.js
(function(angular){ function HeroDetailController(){ } angular.module('ComponentTestApp') .component('heroDetail',{ templateUrl:'views/heroDetail.html', controller:HeroDetailController, bindings:{ hero:'=' } });})(angular);在heroDetail.js 中 , 我們聲明 heroDetail 的 component ,這里要注意 在index.html中以橫杠分離展示的標簽,在js代碼中需要使用駝峰標示展示。其中的 : bindings 對象,表示 component 之中通訊的協議。
現在是頁面中的展示效果:
在我們使用 bindings 進行數據綁定的時候 , 官方并不推薦我們使用 “=” 進行數據綁定, 因為“=” 是一種雙向的數據綁定,這就意味著我們在 component中去修改 數據的時候,在它的父組件中的值也會被修改 。 官方推薦我們使用 “< ” 進行單向的數據綁定,值得注意的是 就算我們使用的是 “<” 因為在父組件和組件作用域都是引用同一個對象的,因此如果要更改組件中的對象屬性或數組元素,父組件仍將反映該更改。
OK,介紹完了 數據的綁定,那么Component與父組件方法之間的綁定又是如何進行的那 ? 讓我們來看下面這個例子
index.html
<!DOCTYPE html><html lang="en" ng-app="ComponentTestApp"><head> <meta charset="UTF-8"> <title>Document</title></head><body ng-controller="MainCtrl as ctrl"> <hero-detail on-log="ctrl.log(text)"></hero-detail> <script src="js/angular.js"></script> <script src="js/index.js"></script> <script src="js/heroDetail.js"></script></body></html>index.js
(function(angular){ angular.module('ComponentTestApp',[]) .controller('MainCtrl',function(){ this.log = function(text){ console.log("輸出的內容為: " + text); } });})(angular);heroDetail.html
<input type="text" placeholder="被輸出的內容" ng-model="text"><br><button ng-click="onLog()">outputLog</button>heroDetail.js
(function(angular){ function HeroDetailController($scope){ $scope.text = ''; var ctrl = this; $scope.onLog = function(){ ctrl.onLog({text:$scope.text}); } } angular.module('ComponentTestApp') .component('heroDetail',{ templateUrl:'views/heroDetail.html', controller:HeroDetailController, bindings:{ onLog:'&' } });})(angular);在代碼中我們通過 “&” 符號去綁定了一個方法 onLog() 該方法接收一個 text 參數 , 需要注意的是,在參數進行傳遞的時候,是以json的形式進行傳遞的 。 這樣我們在點擊 outputLog按鈕的時候,就會輸出我們在input中輸入的內容。
新聞熱點
疑難解答