因本人水平有限,不足之处还望大家指正。
先上图:
我们在开发网页或APP应用时,都会遇到很多个页面,它们的header和footer都是一样的。传统的开发中,我们必须在每一个页面都要写相同的header和footer的代码,这样就造成了重复的代码,而且一旦需求发生变化,header和footer需要重新写时,我们就要将每一个页面的header和footer都要改动,工作量可想而知。
angular.js的指令为我们解决了这个问题,我们只要封装我们需要的指令,用的时候只是调用。如果需求变了,我们只需改动指令中的页面,就好了。
index.html:
<!DOCTYPE HTML>
<html ng-app="myapp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0">
<title>Angular3</title>
<script type="text/javascript" charset="utf-8" src="angular.min.js"></script>
<script type="text/javascript" charset="utf-8" src="directive.js"></script>
<style type="text/css">
*{margin:0px;padding:0px;}
div{text-align:center;line-height:100px;}
.header{width:100%;height:100px;background:red;}
.footer{position:absolute;left:0px;bottom:0px;width:100%;height:100px;background:green;}
</style>
</head>
<body>
<header></header>
<footer></footer>
</body>
</html
header.html:
<div class="header">
这是header
</div
footer.html:
<div class="footer">
这是footer
</div
directive.js(封装的指令):
angular.module("myapp",[]).directive("header",function(){
return {
templateUrl:"Header.html",
restrict:"E"
}
}).directive("footer",function(){
return {
templateUrl:"Footer.html",
restrict:"E"
}
})
大家注意在使用directive("header",function(){});这里的指令“header”要小写,同样的在调用也要小写,<header></header>,最好建议写成“headerContainer”,以免和h5的元素标签<header></header>,<footer></footer>起冲突。
当然了我们也可以将其他需要重复用的代码,封装成指令,用时调用。angular.js中的指令功能和react.js中的组件有点相似。