创建自定义的指令
除了 AngularJS 内置的指令外,我们还可以创建自定义指令。
你可以使用 .directive 函数来添加自定义的指令。
要调用自定义指令,HTML 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
restrict 值可以是以下几种:
E作为元素名使用A作为属性使用C作为类名使用M作为注释使用
restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。
例1 restrict指令==hello指令
<!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">
<hello></hello><!-- E元素 -->
<div class="hello"></div><!-- C样式 -->
<div hello></div><!-- A属性 -->
<!-- directive:hello --><!-- M注释 -->
<script>
var app = angular.module("myApp", []);
app.directive("hello", function() {
return {
restrict : "ACEM",//A属性 C样式 E元素 M注释
replace : true,
template : "<h1>自定义指令222!</h1>"
};
});
</script>
</body>
</html>
本文详细介绍了如何在AngularJS中创建自定义指令,包括使用.directive函数添加指令的方法,以及如何通过不同方式调用这些指令,如元素名、属性、类名和注释。提供了示例代码展示自定义指令的实现。
9321

被折叠的 条评论
为什么被折叠?



