AngularJS 自定義指令詳解及實例代碼
AngularJS支持用戶自定義標簽屬性,在不需要使用DOM節(jié)點操作的情況下,添加自定義的內(nèi)容。
前面提到AngularJS的四大特性:
1 MVC
2 模塊化
3 指令
4 雙向數(shù)據(jù)綁定
下面將會介紹如下的內(nèi)容:
1 如何自定義指令
2 自定義指令的使用
3 自定義指令的內(nèi)嵌使用
如何自定義指令:
Angular是基于模塊的框架,因此上來肯定要創(chuàng)建一個自己的模塊:
var myAppModule = angular.module("myApp",[]);
然后在此模塊基礎(chǔ)上創(chuàng)建指令directive
myAppModule.directive("xingoo",function(){ return{ restrict:'AECM', template:'<div>hello my directive</div>', repalce:true } });
其中,xingoo是我們自定義標簽的名字,后面跟著它的方法函數(shù)。
函數(shù)return了一個鍵值對組合,其中定義了標簽的使用方法、屬性等等內(nèi)容。
那么看看它都定義了哪些內(nèi)容吧:
1 restrict:定義了標簽的使用方法,一共四種,分別是AECM
2 template:定義標簽的模板。里面是用于替換自定義標簽的字符串
3 repalce:是否支持替換
4 transclude:是否支持內(nèi)嵌
如何使用指令:
上面提到了標簽的四種使用方法,即AECM。
A attribute屬性:當做屬性來使用
<div xingoo></div>
E element元素:當做標簽元素來使用
<xingoo></xingoo>
C class類:當做CSS樣式來使用
<div class="xingoo"></div>
M comments注釋:當做注釋使用(這種方式在1.2版本下親測不可用?。?/p>
<!-- directive:xingoo -->
<div></div>
一般來說推薦,當做屬性和元素來使用。
當想要在現(xiàn)有的html標簽上擴展屬性時,采用屬性的方式。
當想要自定義標簽時,采用標簽的形式。
想要使用那種方式,必須要在定義directive中的restrict里面聲明對應(yīng)的字母。
指令的內(nèi)嵌使用:
因為標簽內(nèi)部可以嵌套其他的標簽,因此想要在自定義標簽中嵌套其他的元素標簽,則需要:
1 使用transclude屬性,設(shè)置為true。
2 并使用ng-transclude屬性,定義內(nèi)部嵌套的位置。
代碼如下:
myAppModule.directive("test",function(){ return{ restrict:'AECM', transclude:true, template:"<div>haha! <div ng-transclude></div> wuwu!</div>" } });
全部代碼
<!doctype html> <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body> <xingoo></xingoo> <div xingoo></div> <div class="xingoo"></div> <!-- directive:xingoo --> <div></div> <hr> <xingoo>3333</xingoo> <hr> <test>4444</test> <script type="text/javascript"> var myAppModule = angular.module("myApp",[]); myAppModule.directive("xingoo",function(){ return{ restrict:'AECM', template:'<div>hello my directive</div>', repalce:true } }); myAppModule.directive("test",function(){ return{ restrict:'AECM', transclude:true, template:"<div>haha! <div ng-transclude></div> wuwu!</div>" } }); </script> </body> </html>
運行結(jié)果
以上就是對AngularJS 自定義指令的資料整理,后續(xù)繼續(xù)補充相關(guān)資料,謝謝大家對本站的支持!
- 深入講解AngularJS中的自定義指令的使用
- AngularJS創(chuàng)建自定義指令的方法詳解
- AngularJS優(yōu)雅的自定義指令
- AngularJS使用自定義指令替代ng-repeat的方法
- AngularJS自定義指令實現(xiàn)面包屑功能完整實例
- AngularJS實現(xiàn)自定義指令與控制器數(shù)據(jù)交互的方法示例
- AngularJS 自定義指令詳解及示例代碼
- AngularJS自定義指令之復(fù)制指令實現(xiàn)方法
- AngularJS自定義指令詳解(有分頁插件代碼)
- 詳解angularJS自定義指令間的相互交互
- AngularJS實現(xiàn)自定義指令及指令配置項的方法
相關(guān)文章
Angular ng-repeat 對象和數(shù)組遍歷實例
這篇文章主要介紹了Angular ng-repeat對象和數(shù)組遍歷的相關(guān)資料,并附代碼示例,需要的朋友可以參考下2016-09-09AngularJS 監(jiān)聽變量變化的實現(xiàn)方法
今天小編就為大家分享一篇AngularJS 監(jiān)聽變量變化的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10使用 Github Actions 自動部署 Angular 應(yīng)用到 Github Pages的方法
這篇文章主要介紹了使用 Github Actions 自動部署 Angular 應(yīng)用到 Github Pages,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

詳解Angularjs 如何自定義Img的ng-load 事件