指令也是一种 服务,只是这种服务的定义有几个特殊要求:
配置项 | 类型 | 含义 |
---|---|---|
template | string | 使用template指定的HTML标记替换指令内容(或指令自身) |
restrict | string | 用来限定指令在HTML模板种出现的位置(E,A,C,M) |
replace | true,falset | 是否替换原有的DOM元素 |
transclude | true,false,’element’ | 是否保留原有指令的内部元素 |
scope | true,false,{} | scope属性为指令创建私有的作用域 |
link | function | link属性是一个函数 |
link
<html ng-app="zz">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body>
<span zz-c>我是spanspan>
body>
<script src="js/angular.js">script>
<script type="text/javascript">
angular.module('zz',[])
.directive('zzC',function(){
return{
link:function(scope,element,attrs){
element.on('mouseover',function(){
element.css({outline:'#ff0000 dotted thick'});
}).on('mouseout',function(){
element.css({outline:'none'});
})
}
}
})
script>
html>
restrict
<html ng-app="zz">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body>
<hell>hell>
<div hell>div>
<div class="hell">div>
body>
<script src="js/angular.js">script>
<script type="text/javascript">
angular.module('zz',[])
.directive('hell',function(){
return{
replace:true,
restrict:'ECMA',
template:'hell
'
}
})
script>
html>
scope绑定策略
类型 | 用法 |
---|---|
@ | 把当前属性作为字符串传递,你还可以绑定来自外层scope上的值,从属性种插入{{}}即可 |
= | 与父scope中的属性进行双向绑定 |
&s | 传递一个来自父scope中的函数,稍后调用 |
complie和link
不成功时会保留原样,并在model增加一个$error对象
click
<html ng-app="zz">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body ng-controller="cc">
时间格式:<input type="text" ng-model="format" />br>
当前时间:<span current-time="format">span>
body>
<script src="js/angular.js">script>
<script type="text/javascript">
angular.module('zz',[]).controller('cc',function($scope){
$scope.format='M/d/yy h:mm:ss a';
}).directive('currentTime',function($interval,dateFilter){
return{
link:function(scope,element,attrs){
function upatetime(){
element.text(dateFilter(new Date(),scope.format));
}
$interval(function(){
upatetime();
},1000);
}
}
})
script>
html>
指令交互
<html ng-app="zz">
<head>
<meta charset="UTF-8">
<title>title>
<link rel="stylesheet" href="js/bootstrap.min.css"/>
head>
<body>
<div class="container">
<div class="jumbotron text-center">
<girl beautiful clever>girl>
{{desc}}
div>
div>
<script src="js/angular.js">script>
<script type="text/javascript">
angular.module('zz',[]).directive('girl',function(){
return {
restrict:'E',
controller:function($scope,$element,$attrs){
$scope.desc=[];
this.add=function(char){
$scope.desc.push(char);
console.log($scope.desc)
}
},
template:'angular bb
'
}
}).directive('beautiful',function(){
return {
restrict:'A',
require:'girl',
link:function(scope,element,attrs,grilCtrl){
grilCtrl.add('beautiful');
}
}
}).directive('clever',function(){
return {
restrict:'A',
link:function(scope,element,attrs){
scope.desc.push('clever');
}
}
})
script>
body>
html>