angularjs 创建自定义的指令
创建自定义的指令
除了 AngularJS 内置的指令外,我们还可以创建自定义指令。
你可以使用 .directive 函数来添加自定义的指令。
要调用自定义指令,HTMl 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
你可以通过以下方式来调用指令:
- 元素名
- 属性
- 类名
- 注释
以下实例方式也能输出同样结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<body ng-app="myApp">
<p>元素名</p>
<runoob-directive></runoob-directive>
<p>类名</p>
<div class="class-directive"></div>
<p>属性</p>
<div attribute-directive></div>
<p>注释</p>
<!-- directive: commance-directive -->
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<div><ul><li>1</li><li>1</li><li>1</li><li>1</li></ul></div>"
};
});
app.directive("classDirective", function() {
return {
restrict: "C",
template : "<div><ul><li>must set the restrict : \"C\"</li><li>class directive</li><li>class directive</li><li>class directive</li></ul></div>"
};
});
app.directive("attributeDirective", function() {
return {
template : "<div><ul><li>Attribute directive</li><li>Attribute directive</li></ul></div>"
};
});
app.directive("commanceDirective", function() {
return {
restrict : "M",
replace : true,
template : "<div><ul><li>commance directive</li><li>commance directive</li></ul></div>"
};
});
</script>
</body>
</body>
</html>
限制使用
你可以限制你的指令只能通过特定的方式来调用。
E
只限元素名使用A
只限属性使用C
只限类名使用M
只限注释使用
restrict 默认值为 EA
, 即可以通过元素名和属性名来调用指令。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步