用requirejs把ionic项目模块化

xiaoxiao2021-02-27  372

新建项目什么的就不计了,直接开始。 一.项目的结构如图:

二.主要部分 1.首页的修改: 去掉那些引用的js,添加一个 <script data-main="js/main" src="lib/require.js"></script> 代码如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>TEST</title> <link type="text/css" href="lib/ionic/css/ionic.css" rel="stylesheet"> <link rel="stylesheet" href="css/index.css"> </head> <body ng-controller="mainCtrl as mc" class="platform-android platform-cordova platform-webview"> <ion-nav-view></ion-nav-view> <script src='cordova.js'></script> <script data-main="js/main" src="lib/require.js"></script> </body> </html>

2.main.js的编写

require.config({ paths:{ fastclick:'../lib/fastclick', async:'../lib/async', domReady:'../lib/domReady', angular:'../lib/ionic/js/angular/angular', angularAnimate:'../lib/ionic/js/angular/angular-animate', angularSanitize:'../lib/ionic/js/angular/angular-sanitize', uiRouter:'../lib/ionic/js/angular-ui/angular-ui-router', ngResource:'../lib/ionic/js/angular/angular-resource', ionic:'../lib/ionic/js/ionic', ionicAngular:'../lib/ionic/js/ionic-angular', app:'app', config:'config', services:'services/services', mainServices:'services/mainServices', indexServices:'services/indexServices', moreServices:'services/moreServices', backButtonServices:'services/backButtonServices', chatsServices:'services/chatsServices', chatsCtrl:'controllers/chatsCtrl', chatsdetailCtrl:'controllers/chatsdetailCtrl', mainCtrl:'controllers/mainCtrl', indexCtrl:'controllers/indexCtrl', sortCtrl:'controllers/sortCtrl', moreCtrl:'controllers/moreCtrl', controllers:'controllers/controllers', directives:'directives/directives', mainDirective:'directives/mainDirective', }, waitSeconds: 40, shim:{ cordova:{exports: 'cordova'}, cordovaDevice:{deps: ['cordova'], exports: 'cordovaDevice'}, cordovaSplashScreen:{deps: ['cordova'], exports: 'cordovaSplashScreen'}, cordovaStatusbar:{deps: ['cordova'], exports: 'cordovaStatusbar'}, cordovaKeyboard:{deps: ['cordova'], exports: 'cordovaKeyboard'}, angular : {exports : 'angular'}, app : {exports : 'app'}, angularAnimate : {deps: ['angular']}, angularSanitize : {deps: ['angular']}, uiRouter : {deps: ['angular']}, ngResource: {deps: ['angular']}, ionic : {deps: ['angular'], exports : 'ionic'}, ionicAngular: {deps: ['angular', 'ionic','uiRouter', 'angularAnimate', 'angularSanitize', 'ngResource'],exports: 'ionicAngular'} }, priority:['angular','ionic'], deps:['bootstrap'] });

注:bootstrap是启动项,angular 初始化,具体内容为:

define(['ionic', 'angular', 'routes', 'app'], function (ionic, angular,routes, app) { 'use strict'; var $html, onDeviceReady = function () { angular.bootstrap(document, [app['name']]); }; if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) { // URL: Running in Cordova/PhoneGap document.addEventListener("deviceready", onDeviceReady, false); } if (typeof cordova === 'undefined') { $html = angular.element(document.getElementsByTagName('html')[0]); angular.element().ready(function () { try { angular.bootstrap(document, [app['name']]); } catch (e) { console.error(e.stack || e.message || e); } }); } });

3.app.js的编写(创建app module,这里直接把service和controller进行了分离):

define(['angular', 'ionic', 'uiRouter', 'ionicAngular', 'services', 'controllers' ], function (angular,ionic ,uiRouter) { 'use strict'; var app = angular.module('app', [ 'ngResource', 'ionic', 'app.controllers', 'app.services', 'ui.router' ]); return app; });

注:这里把service和controller进行了分离,新建两个文件夹,分别命名为service和controller,之后把在各自文件夹内新建同名的js,便于文件的分离和关联。 controller.js的编写:

define(['app', 'mainCtrl', 'indexCtrl', 'moreCtrl','chatsCtrl','chatsdetailCtrl', 'services'], function(app){ 'use strict'; var controllers = angular.module('app.controllers', ['app.services', 'app.config']); controllers.controller('mainCtrl', require('mainCtrl')); controllers.controller('indexCtrl', require('indexCtrl')); controllers.controller('moreCtrl', require('moreCtrl')); controllers.controller('chatsCtrl', require('chatsCtrl')); controllers.controller('chatsdetailCtrl', require('chatsdetailCtrl')); return controllers; });

services.js的编写:

define(['app','config', 'mainServices', 'indexServices','moreServices','backButtonServices','chatsServices'], function (app) { 'use strict'; var config = require('config'), services = angular.module('app.services', ['app.config', 'ngResource']); services.factory('$mainServices', require('mainServices')); services.service('$indexServices', require('indexServices')); services.service('$moreServices', require('moreServices')); services.factory('$backButtonServices', require('backButtonServices')); //通讯录(chats页面) services.service('$chatsServices',require('chatsServices')); return services; });

这样基本的框架就好了,下面就是具体页面的编写及服务调用。 其实上面的代码中已经有需要的js文件了,这里具体说明一下: 根据文件的结构可以看出来大致分为3块,首页、chats和更多的页面。 这里调数据都是统一写的本地的假数据。 首页json:

{ "banner": { "item":[ { "img":"images/tmp/1.jpg", "url":"www.baidu.com" }, { "img":"images/tmp/2.jpg", "url":"http://www.sina.com.cn/" }, { "img":"images/tmp/3.jpg", "url":"http://www.qq.com/" } ] }, "coupon": { "item": [ { "time": "2016.01.01-2017.05.14", "money": 787, "use": 7878, "isGet": 0, "url": "http://mall.e-wj.dev:40080/store/41" }, { "time": "2016.01.01-2017.05.14 ", "money": 787, "use": 7878, "isGet": 1, "url": "http://mall.e-wj.dev:40080/store/44" } ] }, "tejia": { "item": [ { "url": "http://mall.e-wj.dev:40080/ware/43", "img": "http://image.tianjimedia.com/uploadImages/2011/306/EQ2E3ZUPNMNV.jpg", "name": "test_1_特卖", "nowMoney": 40, "oldMoeny": 45 }, { "url": "http://mall.e-wj.dev:40080/ware/43", "img": "../../json/60.jpg", "name": "test_2_特卖", "nowMoney": 40, "oldMoeny": 45 }, { "url": "http://mall.e-wj.dev:40080/ware/43", "img": "http://tupian.qqjay.com/u/2013/1127/19_222949_14.jpg", "name": "test_3_特卖", "nowMoney": 40, "oldMoeny": 45 }, { "url": "http://mall.e-wj.dev:40080/ware/43", "img": "http://tupian.qqjay.com/u/2013/1127/19_222949_14.jpg", "name": "test_4_特卖", "nowMoney": 40, "oldMoeny": 45 } ] } }

chats页json:

{ "data": { "item":[{ "id": 0, "name": "Ben Sparrow", "lastText": "You on your way", "face": "img/ben.png" }, { "id": 1, "name": "Max Lynx", "lastText": "Hey, its me", "face": "img/max.png" }, { "id": 2, "name": "Adam Bradleyson", "lastText": "I should buy a boat", "face": "img/adam.jpg" }, { "id": 3, "name": "Perry Governor", "lastText": "Look at my mukluks", "face": "img/perry.png" }, { "id": 4, "name": "Mike Harrington", "lastText": "This is wicked good ice cream.", "face": "img/mike.png" }] } }

页面的完整代码如下: 首页html:

<ion-view view-title="我的首页"> <ion-nav-buttons side="left"> <button class="button button-icon button-clear" ng-click="sideLeftMenu()" ng-class="{true: 'ion-navicon', false:'ion-arrow-left-c'}[isActive.leftActive]"></button> </ion-nav-buttons> <ion-nav-buttons side="right"> <button class="button button-icon button-clear " ng-click="sideRightMenu()" ng-class="{true: 'ion-search', false:'ion-arrow-right-c'}[isActive.rightActive]"></button> </ion-nav-buttons> <ion-content class="has-header" overflow-scroll='false'> <ion-slide-box ng-if="bannerList" on-slide-changed="slideHasChanged($index)" delegate-handle="slideimgs" does-continue="true" auto-play="true" does-continue="true" slide-interval="2000"> <ion-slide ng-repeat="b_item in bannerList"> <a ng-href="{{b_item.url}}" > <img src="{{b_item.img}}" class="full-image" > </a> </ion-slide> </ion-slide-box> <div class="padding"> <h2>Welcome to Ionic</h2> <p> This is the Ionic starter for tabs-based apps. For other starters and ready-made templates, check out the <a href="http://market.ionic.io/starters" target="_blank">Ionic Market</a>. </p> <p> To edit the content of each tab, edit the corresponding template file in <code>www/templates/</code>. This template is <code>www/templates/tab-dash.html</code> </p> <p> If you need help with your app, join the Ionic Community on the <a href="http://forum.ionicframework.com" target="_blank">Ionic Forum</a>. Make sure to <a href="http://twitter.com/ionicframework" target="_blank">follow us</a> on Twitter to get important updates and announcements for Ionic developers. </p> <p> <b>Psst!</b> - Try <a href="http://view.ionic.io/">Ionic View</a> to easily share and test your app with clients and co-workers. </p> </div> <div class="pane-list pane-list-te"> <div class="pane-list-top row"> <em></em> <h3>本周特价</h3> <a href="" class="pane-list-top-btn">查看更多</a> </div> <ul class="row"> <li class="col col-50" ng-repeat="t_item in dazheList"> <a href="{{t_item.url}}"> <img ng-src="{{t_item.img}}"> </a> <p class="pane-list-te-name" ng-bind="t_item.name"></p> <div> <span class="pane-list-te-nm" ng-bind="'¥'+t_item.nowMoney"></span> <span class="pane-list-te-om" ng-bind="'¥'+t_item.oldMoeny"></span> </div> </li> </ul> </div> </ion-content> </ion-view>

首页controller.js:

define(['mainCtrl'], function () { 'use strict'; function ctrl($scope, $mainServices, $indexServices, $ionicTabsDelegate, $ionicSlideBoxDelegate) { $mainServices.showLoading(); $indexServices.get(function(data){ console.log(data) if(data !== null && data !== undefined){ $mainServices.hideLoding(); } $scope.bannerList = data.banner.item; $scope.couponList = data.coupon.item; $scope.dazheList = data.tejia.item; }); } ctrl.$inject = ['$scope', '$mainServices', '$indexServices', '$ionicTabsDelegate', '$ionicSlideBoxDelegate']; return ctrl; });

首页services.js:

define(function(){ 'use strict' var service = function($http){ return { get:function(callback){ $http.get('../../json/index.json').success(function(data){//本地地址 return callback(data); }); } } }; service.$inject = ['$http']; return service; });

切换页面html:

<ion-side-menus> <ion-side-menu-content> <ion-nav-bar class="bar-energized nav-title-slide-ios7 title-main"> <ion-nav-back-button class="button-icon"> <span class="icon ion-ios7-arrow-left"></span> </ion-nav-back-button> </ion-nav-bar> <!--tabs start--> <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <ion-tab title="首页" icon-off="ion-ios-home-outline" icon-on="ion-ios-home" href="#/tab/index"> <ion-nav-view name="tab-index"></ion-nav-view> </ion-tab> <ion-tab title="chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/chats"> <ion-nav-view name="tab-chats"></ion-nav-view> </ion-tab> <ion-tab title="更多" icon-on="ion-ios-more-outline" icon-off="ion-ios-more" href="#/tab/more"> <ion-nav-view name="tab-more"></ion-nav-view> </ion-tab> </ion-tabs> <!--tabs end--> </ion-side-menu-content> <!-- 左侧滑动 --> <ion-side-menu side="left" > <!-- <div ng-include="'/templates/etc/sideMenuLeft.html'"></div> --> <ion-header-bar class="bar bar-header bar-dark"></ion-header-bar> <ion-content has-header="true" drag-content="true"> <ion-list> <ion-item href="#">我是侧边栏(无用1号)</ion-item> <ion-item href="#">我是侧边栏(无用2号)</ion-item> <ion-item href="#">我是侧边栏(无用3号)</ion-item> </ion-list> </ion-content> </ion-side-menu> <!-- 右侧滑动 --> <ion-side-menu side="right"> <ion-header-bar class="bar bar-header bar-dark"> <label class="item item-input stable-dark" > <input type="search" class="dark" placeholder="我是搜索框(但是没用)"/> </label> <button class="button right-button button-icon button-clear ion-search"></button> </ion-header-bar> <ion-content has-header="true"></ion-content> </ion-side-menu> </ion-side-menus>

chats页面html:

<ion-view view-title="chats"> <style type="text/css"> </style> <ion-nav-buttons side="left"> <button class="button button-icon button-clear" ng-click="sideLeftMenu()" ng-class="{true: 'ion-navicon', false:'ion-arrow-left-c'}[isActive.leftActive]"></button> </ion-nav-buttons> <ion-content scroll="true" class=""> <ion-list> <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.chatdata}}"> <img ng-src="{{chat.face}}"> <h2>{{chat.name}}</h2> <p>{{chat.lastText}}</p> <i class="icon ion-chevron-right icon-accessory"></i> </ion-item> </ion-list> </ion-content> </ion-view>

对应的chatsCtrl.js(controller):

define(function () { 'use strict'; function ctrl($scope, $mainServices,$chatsServices) { $mainServices.showLoading(); $chatsServices.get(function(data){ angular.forEach(data.data.item,function(i){console.log(i) i.chatdata=encodeURIComponent(encodeURIComponent(JSON.stringify(i))) }) $scope.chats = data.data.item;console.log($scope.chats) }); $mainServices.hideLoding(); } ctrl.$inject = ['$scope', '$mainServices','$chatsServices']; return ctrl; });

对应调的服务chatsServices(services):

define(function(){ 'use strict' var service = function($http){ return { get:function(callback){ $http.get('../../json/chats.json').success(function(data){//本地地址 return callback(data); }); } } }; service.$inject = ['$http']; return service; });

chats详情页面html:

<ion-view view-title="{{chat.name}}"> <ion-content class="padding"> <img ng-src="{{chat.face}}" style="width: 64px; height: 64px"> <p> {{chat.lastText}} </p> </ion-content> </ion-view>

详情页面的chatsdetailCtrl.js:

define(function () { 'use strict'; function ctrl($scope, $mainServices,$stateParams) { $scope.chat = JSON.parse(decodeURIComponent(decodeURIComponent($stateParams.chatdata))); //$scope.chat = JSON.parse($stateParams.chat);console.log(typeof $scope.chat) console.log($stateParams.chatdata) } ctrl.$inject = ['$scope', '$mainServices','$stateParams']; return ctrl; });

注:这里详情的信息是从chats页面整体带过来的对象,必须进行编码,里面有符号的问题,不进行两次编码则会使页面跳转出问题或者传参不全报错等。

除此之外,有个routes.js用来写页面间的跳转之类的:

define(['app'], function(app) { 'use strict'; app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: '/tab', abstract: true, templateUrl: 'templates/tabs.html' }) // Each tab has its own nav history stack: .state('tab.index', { url: '/index', views: { 'tab-index': { templateUrl: 'templates/site/index.html', controller: 'indexCtrl' } } }) .state('tab.chats', { url: '/chats', views: { 'tab-chats': { templateUrl: 'templates/chats/index.html', controller: 'chatsCtrl' } } }) .state('tab.detail', { url: '/chats/:chatdata', views: { 'tab-chats': { templateUrl: 'templates/chats/detail.html', controller: 'chatsdetailCtrl' } } }) .state('tab.more', { url: '/more', views: { 'tab-more': { templateUrl: 'templates/etc/more.html', controller: 'moreCtrl' } } }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/index'); }]); });

最终效果为: 首页:

chats页:

chats详情页:

最后的最后:完整项目文件地址为(可下载): http://download.csdn.net/detail/zuoyiran520081/9833456

转载请注明原文地址: https://www.6miu.com/read-3701.html

最新回复(0)