目录
- directive语法
- return 的参数说明
- directive与controller的交互
- directive间的交互
- 三种绑定策略
一、directive语法
app.directive("name",function(){
return {
....
}
})
或
.directive("name",function(){
return {
....
}
})
//根据实际需要选择参数,
二、return 的参数说明
restrict
...
restrict:"AEMC"
...
//限定指令能用作什么,常用的是'AE'
//其中:A(属性),E(元素),M(注释),C(样式类)
template类
直接写模板:
template:"<div>这是放置代码</div>"
通过文件作模板:
templateUrl:"xxx.html"
//此时要注意html文件放置的路径问题
常用直接模板缓存问题(少见)
app.run(function($templateCache){
$templateCache.put("name.html","<div>这里放置代码</div>");
})
//缓存多用的html文件(指直接写的,引入文件作模板可以不用管)
----------
//然后template要这样写
template:$templateCache.get("name.html")
跟replace参数协调使用
当replace:true
时默认为直接替代标签内的内容,若不想直接替代可这样:
transclude:true,
template:"<div ng-transclude></div>+你的代码"
require与link
require:"^xxx",
//^的意思是从所有的指令列表中找你要的
//填写你所依赖的指令,然后你可以使用你依赖指令里的controller内容link:function(scope,element,attrs,xxxCtrl){
...
}
//注意你用require获取了的指令,会把获取的指令的controller作为第四个参数传给link
scope
//解决跨域问题,就算里面无值,最好也写上去
scope:{}
controller
当其他指令依赖你的时候,可以使用controller里的属性或函数
三、directive与controller的交互
例子如下:
app.controller('ctrl',function($scope){
$scope.alert = function(a){
alert(a);
}
})
app.directive('check',function(){
return{
restrict:'AE',
link:function(scope,element,attr){
element.bind('click',function(){
scope.alert(this.innerHTML);
})
}
}
})
//创建一个check的指令,当这个指令的元素被点击时会触发controller里的alert函数,打印出元素里的内容。实现controller与directive的交互
四、directive间的交互
原理:若a指令依赖与b指令,则a指令可使用b指令里controller里的属性和函数
.directive("b",function(){
return {
restrict:'AE',
controller:function($scope,$element,$attrs,$transclude){
$scope.name="alex",
this.alert=function(a){
alert(a)
}}}})
----------
.directive("a",function(){
return {
restrict:'AE',
require:"^b",
link:function(scope,element,attrs,bCtrl){
bCtrl.alert(scope.name)
}
}})
五、三种绑定策略
‘@’绑定策略(通常用于绑定字符串)
html文件
<div ng-controller="ctrl">
<direct ostr="{{str}}"></direct>
<div>
js文件
.directive("direct",function(){
return{
restrict: 'AE',
template: '<div>{{ str }}</div>',
scope:{
str:'@ostr'
//这里的str是提供给template的
}
}
})
.controller("ctrl",function($scope){
$scope.str="this is a string";
});
‘=’绑定策略(通常用于双向绑定)
html文件
<div ng-controller="ctrl">
<input ng-model="str"/>
<direct model="str"/></direct>
</div
js文件
app.directive("direct",function(){
return{
restrict: 'ECMA',
template: '<div>指令中:<input ng-model="model"/></div>',
scope:{
model:'='
}
}
})
app.controller("ctrl",function($scope){
$scope.str="aaa"
});
‘&’绑定策略(通常用于传递函数)
html文件
<div ng-controller="ctrl">
<direct show="showName(name)"></direct>
</div>
js文件
app.directive("direct",function(){
return{
restrict: 'ECMA',
template: '
<div><input ng-model="model"/></div>
'+'
<
div><button ng-click="show({name:model})">show</button>',
scope:{
show:'&'
}
}
})
app.controller("ctrl",function($scope){
$scope.showName=function(name){
alert(name);
}
});