angularJS 自定義指令
阿新 • • 發佈:2019-01-29
angularJS 自定義屬性
類似於過濾器filter,內建了許多方法同時可以自定義方法。
通過angular.model來建立模組物件:
-angular.model:
- controller:控制器
- run:初始化
- filter:過濾器
- directive:建立自定義(myHello->my-hello)
-restrict有四種定義的方式(注意大小寫):指定指令型別並可疊加使用
》E:元素,標籤(重寫HTML中的標籤屬性或者替換標籤模板)
》A:屬性(主要是功能性如:ng-if)
》C:class的方式,看做指令。但容易與class的樣式混淆
》M:註釋(注意空格)
—template:模板選項
-templateUrl:外部模板引用
-replace:替換(true:替換) - scope
-獨立作用域true,互相獨立不影響
-隔離作用域{},不再與外面巢狀的標籤再有任何繼承的關係
繫結策略:用來繫結不同的資料
》@:繫結資料,繫結指令,繫結的普通字串
》=:繫結資料,變數名
》&:函式傳遞
程式碼示例:
<script>
var m = angular.module('myApp',[]);//引入相應模組
m.directive('hello',function(){//通過函式回撥的形式
return{
restrict:'EAMC' ,//配置選項
replace:true,
template:'<div>hello angular </div>'
};
});
</script>
<hello></hello>
<p hello></p>
<p class="hello"></p>
<!-- directive:hello --><!--注意空格-->
<div ng-controller ="Aaa" >
</div>
頁面結果展示:
程式碼示例:
<script>
var m = angular.module('myApp',[]);//引入相應模組
m.directive('myTab',function(){//通過函式回撥的形式
return{
restrict:'E',//配置選項
replace:true,
//scope:true,//獨立
scope:{
myId:'@',
myName:'=',
myFn:'&'
},//隔離作用域
controller:['$scope',function($scope){
$scope.name = 'miaov';
}],
template:'<div id="{{myId}}">\
<input class="active" type="button" value="1" ng-click="myFn({num:456})">\
<input type="button" value="2">\
<input type="button" value="3">\
<div style="display:block">{{name}}</div>\
<div>22222222</div>\
<div>33333333</div>\
</div>'
};
});
m.controller('Aaa',['$scope',function($scope){
$scope.name = 'hello';
$scope.show = function(n){
alert(n);
}
}]);
</script>
<body ng-controller="Aaa">
<my-tab my-id="div1" my-name="name" my-fn="show(num)"></my-tab>
<my-tab my-id="div2" my-name="name" my-fn="show(num)">></my-tab>
頁面結果展示:
6.link:進行dom操作
》scope:作用域
》elemen:指的是父級的元素
》attr:當前標籤上的屬性
》reController