angular指令:自定义html元素
包括:
- 自定义标签
- 自定义属性
创建一个简单指令:
app.directive('first', [function(){
return {
restrict: 'AE', //指令使用位置,默认AE
template: '<h1>First Directive! Oh! Oh! Oh!</h1>'
};
}]);
指令使用
<first></first>
<div first></div>
<la first></la>
first解析
- directive方法返回一个对象,其中包含了用来定义和配置指令所需的方法和属性
- restrict:指令使用位置,默认AE
- E 只限元素名使用
- A 只限属性使用
- C 只限类名使用
- M 只限注释使用
- template:指令代表的html模板
- 默认情况下,angular将模板生成的html代码嵌套在自定义标签内部
- 在指令定义中加入‘replace:true’可以将自定义标签从DOM中移除
app.directive('first', [function(){
return {
restrict: 'AE', //默认AE
template: '<h1>First Directive! Oh! Oh! Oh!</h1>',
replace: true //移除自定义指令
};
}]);
指令兼容问题(IE)
- 始终用属性声明指令
- 重载内置html标签如:<a><form><input>不会导致浏览器兼容性问题,因为浏览器本身就支持这些标签
向指令中传递数据
//从前,有这样一个指令.....
app.directive('first', [function(){
return {
restrict: 'AE',
template: '<h1>Hello, Tom</h1>',
replace: true
}]);
//其中的"Hello Tom"是写死的,能不能随意替换名字呢?
这里,涉及到指令的独立作用域和值绑定策略
作用域:这里的作用域和C语言中的作用域很相似,是用来隔离变量的。比较熟悉的就是ng-controller的作用域,在controller中通过$scope可以设置作用域的值。不同Controller中可以有同名的值。自作用域中的变量可以引用父作用域里的值,直到rootScope。
如果没有为指令设置独立作用域,它就会继承父作用域。
指令模板内使用变量
app.directive('first', [function(){
return {
restrict: 'AE',
//回到上面那个问题,在模板内使用变量
template: '<h1>Hello, {{name}}</h1>',
replace: true
};
}]);
//此时,指令没有独立作用域,就会使用父作用域里的"name"值,如果父作用域没有,再往上找,直到$rootScope,如果$rootScope里也没有,就不会显示。
创建独立作用域
app.directive('first', [function(){
return {
scope: {}, //创建独立作用域
restrict: 'AE',
template: '<h1>Hello, {{name}}</h1>',
replace: true
};
//AngularJS为指令的scope参数提供了三种选择,分别是:false,true,{};默认false
//false: 使用父作用域
//true: 有独立的作用域(使用父作用域里的变量初始化)
//{}: 脱离外部作用域(常用)
}]);
下面介绍一下”scope:{}”的值绑定策略
三种形式:@, &, =
@绑定
//这种方式传递的是字符串,不会计算
//<first name="Tom"></first>
//如果想传入外部作用域的变量,则需要{{}}:
//<first name="{{name}}"></first>
app.directive('first', [function(){
return {
scope: {
name: '@' //绑定属性name的值
//name: '@myname' 绑定属性myname的值
},
template: '<h1>hello, {{name}}</h1>',
replace: true
};
}]);
=绑定
//这种绑定绑定的是外部对象,在指令模板中可以访问其属性
<body ng-app="app" ng-controller="gcl">
<first user="user"></first>
<script>
var app = angular.module('app', [])
app.controller('gcl', ['$scope', function($scope){
$scope.user={}
$scope.user.name = "TTT"
}])
app.directive('first', [function(){
return {
scope: {
user: '='
//user: '=ta'
},
template: '<h1>hello, {{user.name}}</h1>',
replace: true
};
}]);
</script>
</body>
&绑定
//绑定外部方法
<body ng-app="app" ng-controller="gcl">
<first show="show()"></first>
<script>
var app = angular.module('app', [])
app.controller('gcl', ['$scope', function($scope){
$scope.show = function(){
alert('Hello, world')
}
}])
app.directive('first', [function(){
return {
scope: {
show: '&'
},
template: '<h1 ng-click="show()">hello, world!</h1>',
replace: true
};
}]);
</script>
</body>
唔,关于指令的知识还有好多啊