一、 首先是自定義模板,
var app=angular.module('myapp',[]);
二、然后用自定義的模板去創建自己的指令,千萬注意寫法,雖然和創建控制器有點像但是沒有等號,
app.directive('myBtn',[function(){ return{}}])
注意點:1,括號前面沒有等號 2、第一個參數是自定義指令的名字 3、第二個參數是一個匿名函數,其中記得要有return返回值。
三、返回的參數
template:html代碼
templateUrl:id值 <script id="tpl" type="text/ng-template"> <div class="flag"> <p>{{msg}}</p> <button class="{{mystyle}}" ng-transclude>登陸</button> </div> </script>
這里的id值鏈接到script的id值注意修改type屬性 這種方法為推薦寫法
restrict:"ECA"
這里的意思是設定的指令何時可用:元素,class,屬性
transclude:true/fasle
這個的意思是可以自定義輸入true為可以false為不可以
replace:true/false
這個的意思是否可以替換有該指令的元素
scope:{
mystyle:'@'
}
mystyle可以任意命名,@為固定寫法,它的作用就是粘合模板中的mystyle和頁面的mystyle
link:function(scope,element,attribute){
scope.msg='我是中國人'
element.on('click',function(){
alert('hello')
console.log('attribute')
})
這里的link是關聯自定義指令內部的數據。這個msg在模板中可以直接使用。而element和attribute是對msg而言的
}
完整代碼如下
app.directive('myBtn', [function(){ // 在這里直接return 一個對象就可以了 return { // template屬性,是封裝的ui // template:'<div><button>我是按鈕</button></div>', // A.作用也是提供字符串,對應的內容會被添加到自定義指令所在位置 // 值是一個html文件所在位置 // B. 值也可以是一個script標簽的id // templateUrl:'./01.template.html' templateUrl:'tpl', restrict:'ECA', // Attribute Class Element // 取代,替換 // replace: true, // 為true時,會把模板中的內容替換到自定義上。 // 為true時會把自定義標簽中間的內容,插入到指定的模板中 transclude: true, // 可以得到自定義指令的屬性 scope:{ // @開頭,表示要獲取自定義指令屬性的值, // 在對應的模板可以直接使用{{tmp}} 來得到mystyle對應的值 // tmp:'@mystyle' mystyle:'@' // 這是上一行的簡寫 }, // 指定一個function link:function(scope,element,attributes){ // 參數: // scope: 類似於控制器時里的$scope,但是這里的scope屬性值是在模板中使用的. scope.msg="我是中國人,我愛自己的祖國!" // element : 指向模板最外層的對象 // 如果replace為true,指向的就是自定義指令所在標簽 console.log(element) element.on('click',function(){ alert('你點我了!') }) // attributes : 這個對象里的屬性就是自定義指令所在標簽的屬性 console.log(attributes) // angular.element console.log('link') } } }])
html的代碼如下
<body ng-app="directiveApp"> <h1>以屬性形式使用: A</h1> <div my-btn test="小明" age="18"></div> <h1>以樣式名形式使用: C</h1> <div class="my-btn"></div> <h1>以自定義標簽形式使用: E</h1> <my-btn mystyle="login"> 注冊!!! </my-btn> <my-btn mystyle="register"> 注冊!!!002 </my-btn>