AngularJS之组件化篇

来源:互联网 发布:龙 知乎 编辑:程序博客网 时间:2024/06/09 23:22

AngularJS组件化:将页面中可以重复使用的标签封装成一个组件,方便这一部分UI重复使用,类似于JS中的函数,封装了一部分处理代码,通过函数调用就可以重复使用这些代码。
组件可以用.component 注册(在 angular.module 创建的module)。这个方法有两个参数:组件名称,组件配置对象(和指令的区别,一个是工厂方法,一个是对象)。
这是一个组件化的小应用:

<!DOCTYPE html><html ng-app="myApp"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="../angular.min.js"></script></head><body><page-header></page-header><page-slide></page-slide><page-footer></page-footer><script>    var app = angular.module("myApp", []);    app.component("pageHeader", {        template:"<h2>尊敬的用户{{username}},欢迎访问本系统</h2>",        controller:function($scope) {            $scope.username = "tom";        }    });    app.component("pageSlide", {        template:"<h2>这是一个侧边栏导航</h2>"    });    app.component("pageFooter", {        template:"<h2>这是一个网页底部代码</h2>"    });</script></body></html>

在实际开发中,很多网站的页面中,header,footer,侧边栏样式是一样的,为了提高代码的复用性,我们可以将header和footer部分封装为组件,在页面中单独引用,便于开发

index.html:<!DOCTYPE html><html ng-app="myApp"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="js/lib/AngularJS/angular.min.js"></script>    <script src="js/app/index/index.js"></script></head><body>    <div class="container">        <page-header></page-header>        <page-slide></page-slide>        <div class="pageBody">            <!-- 网页中要展示的购物车内容 -->        </div>        <page-footer></page-footer>    </div></body></html>
index.js:// 定义了一个模块对象var app = angular.module("myApp", []);app.component("pageHeader", {    templateUrl:"js/app/index/pageHeader/pageHeader.html",    controller:function($scope) {    }});app.component("pageSlide", {    templateUrl:"js/app/index/pageSlide/pageSlide.html",    controller:function($scope) {    }});app.component("pageFooter", {    templateUrl:"js/app/index/pageFooter/pageFooter.html",    controller:function($scope) {    }});

pageHeader.html:

<div class="header-pageHeader">    页面头部</div><style>    .header-pageHeader{        width:100%;        height:200px;        background:#069;        color:#fff;    }</style>

pageFooter.html:

<div class="footer-pageFooter">    页面底部</div><style>    .footer-pageFooter{        clear:both;        width:100%;        height:100px;        background:#888;        color:#fff;    }</style>

pageSlide.html:

<div class="slide-pageSlide">    侧边栏</div><style>    .slide-pageSlide{        float:left;        width:300px;        height:500px;        background:orange;    }</style>
0 0