bootstrap有強大的指令系統,可以自定義一些屬性,基本知識請移步:http://angularjs.cn/A00r http://www.cnblogs.com/lvdabao/p/3391634.html
我參考這兩篇文章所述,封裝了bootstrap的alert和panel控件,現將代碼簡單的貼出來。
注:目前我對ng了解非常淺,沒有關注細節,實現功能第一位,我覺得比較合適的學習路線是,先用起來,在用的過程中不斷深入。
第一步:注冊module
angular.module('app.directives', [])
第二步:定義指令
1.alert的封裝,這個是最簡單的了,只是div上面多了兩個class而已
angular.module('app.directives', []) .directive('successtip', function () { return { restrict: 'E', template: '<div class="alert alert-success" role="alert" ng-transclude></div>', replace: true, transclude: true } })
2.panel的封裝,特點:多層標簽嵌套
特別注意的點是:ng-transclude,這個寫到哪里,完了之后,你的標簽中的內容就會填充在那個節點下面,比如panelheader的定義,用戶將來使用時
<panelheader>content</panelheader>,這里的content會填充到h3下面,而不是div下面.
.directive('panel', function () { return { restrict: 'E', template: '<div class="panel panel-danger" ng-transclude></div>', replace: true, transclude: true } }) .directive('panelheader', function () { return { restrict: 'E', template: '<div class="panel-heading"><h3 class="panel-title" ng-transclude></h3></div>', replace: true, transclude: true } }) .directive('panelbody', function () { return { restrict: 'E', template: ' <div class="panel-body" ng-transclude></div>', replace: true, transclude: true } });
如果你的模板比較復雜,不適合用一個string來寫,那你可以用html模板來放置,只是在directive方法中,你就不能寫template了,而是要寫templateurl,路徑是你定義的html模板的路徑。
第三步:使用
這個時候,使用起來就不需要記那些繁瑣的css和div的層級結構了,只需要記住標簽的層級結構就好,這樣子我個人的感覺是有點面向對象編程的意思了,比較容易理解和記憶。
1.alert的使用
<successtip>登錄成功</successtip>
顯示效果:
2.panel的使用
<panel> <panelheader> panel healer</panelheader> <panelbody>panel Body</panelbody> </panel>
顯示效果:
對於一些復雜的控件,這個封裝就會大大減少開發工作量,我這個目前還是有問題的,我現在是每個顏色都需要封裝一次,我覺得是會有辦法在上面加個屬性能讓他們顯示為不同顏色的。待續...