1.关于restrict:'AECM'
<!DOCTYPE html>
<html ng-app="myModule" lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="angular-1.2.26/angular.js"></script>
<script type="text/javascript" src="HelloAngular_Directive.js"></script>
</head>
<body>
<hello></hello>
<div hello></div>
<div class="hello"></div>
<!-- directive:hello -->
<div></div>
</body>
</html>
var myModule = angular.module("myModule",[]);
myModule.directive("hello",function(){
return {
restrict:'AECM',
template:'<div>Hi everyone!</div>',
replace:true
}
});
restrict:'AECM':
E:元素<hello></hello>
A(默认):属性<div hello></div>
C:样式类 <div class="hello"></div>
M:注释<!-- directive:hello --><div></div>
2.多个指令中使用同一个模板
var myModule = angular.module("myModule",[]);
myModule.run(function($templateCache){
$templateCache.put("hello.html","<div>Hello everyone!!!</div>");
})
myModule.directive("hello",function($templateCache){
return {
restrict:'AECM',
template:$templateCache.get("hello.html"),
replace:true
}
});
3.指令中嵌套普通div标签需要设置replace
<!DOCTYPE html>
<html ng-app="myModule" lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="angular-1.2.26/angular.js"></script>
<script type="text/javascript" src="HelloAngular_Directive.js"></script>
</head>
<body>
<hello>
<div>hello的内部内容</div>
</hello>
<div></div>
</body>
</html>
var myModule = angular.module("myModule",[]);
myModule.directive("hello",function(){
return {
restrict:'AECM',
template:'<div>Hello everyone!<div ng-transclude></div><div>',
transclude:true
}
});
4.控制器内部指令调用控制器中的方法
<!DOCTYPE html>
<html ng-app="myModule" lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="angular-1.2.26/angular.js"></script>
<script type="text/javascript" src="HelloAngular_Directive.js"></script>
</head>
<body>
<div ng-controller="myCtrl">
<loader>滑动加载</loader>
</div>
<div></div>
</body>
</html>
var myModule = angular.module("myModule", []);
myModule.controller('myCtrl', ['$scope', function($scope) {
$scope.loadData = function() {
console.log("加载数据中...");
}
}]);
myModule.directive('loader', function() {
return {
restrict: 'AE',
link: function(scope, element, attr) {
element.bind("mouseenter", function() {
//scope.loadData(); //方式1
scope.$apply('loadData()'); //方式2
});
}
}
});