创建自定义的指令
除了 AngularJS 内置的指令外,我们还可以创建自定义指令。
你可以使用 .directive 函数来添加自定义的指令。
要调用自定义指令,HTML 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, myAngular, 但在使用它时需要以 - 分割, my-angular:
你可以通过以下方式来调用指令:
元素名属性类名注释
元素名
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular-1.6.3/angular.js"></script>
</head>
<body>
<div ng-app="myDirective">
<my-angular></my-angular>
</div>
<script>
var app=angular.module("myDirective",[]);
app.directive("myAngular", function() {//注意名称myAngular---<my-angular>
return {
template : "<p>自定义指令!</p>"
};
});
</script>
</body>
</html>
属性:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div runoob-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定义指令!</h1>"
};
});
</script>
</body>
</html>
类名:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div class="runoob-directive"></div>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "C",
template : "<h1>自定义指令!</h1>"
};
});
</script>
<p><strong>注意:
</strong> 你必须设置
<b>restrict
</b> 的值为 "C" 才能通过类名来调用指令。
</p>
</body>
</html>
注释:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<!-- directive: runoob-directive -->
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "M",
replace : true,
template : "<h1>自定义指令!</h1>"
};
});
</script>
<p><strong>注意:
</strong> 我们需要在该实例添加
<strong>replace
</strong> 属性, 否则评论是不可见的。
</p>
<p><strong>注意:
</strong> 你必须设置
<b>restrict
</b> 的值为 "M" 才能通过注释来调用指令。
</p>
</body>
</html>
限制使用
你可以限制你的指令只能通过特定的方式来调用。
restrict 值可以是以下几种:
E 作为元素名使用A 作为属性使用C 作为类名使用M 作为注释使用
restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。
转载于:https://www.cnblogs.com/dehuachenyunfei/p/6618935.html
相关资源:AngularJS学习第二篇 AngularJS依赖注入