Angularjs+require 单页面笔记

施默
2023-12-01

一 、 HTML部分

    <body>
        <div ui-view></div>
    </body>
    <script src="libs/require/require.js" data-main="main"></script>

二 、 Main入口文件

var APP_VERSION = 1.2;
//初始化
(init());
//检测浏览器是否支持createXmlHttp
function createXmlHttp() {
var xhrobj = false;
try {
// ie msxml3.0+
xhrobj = new ActiveXObject("Msxml2.XMLHTTP"); 
} catch (e) {
try {
// ie msxml 2.6
xhrobj = new ActiveXObject("Microsoft.XMLHTTP"); 
} catch (e2) {
xhrobj = false;
}
}
// firefox opera 8.0
if (!xhrobj && typeof XMLHttpRequest != 'undefined') { 
xhrobj = new XMLHttpRequest();
}
return xhrobj;
}
//init
function init() {
var xhr = createXmlHttp();
  xhr.open("GET", "config/ver.json?ver_=" + (new Date()).getTime(), true);
  xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  xhr.setRequestHeader("If-Modified-Since", "0");


  xhr.onreadystatechange = function(result) {
   if (xhr.readyState == 4) {
      if (xhr.status == 200) {
      // 获得服务器返回的字符串
        var res = xhr.responseText; 
        if (res) {
          var data = JSON.parse(res);
          APP_VERSION = data.version;
          loadMain();
          return;
      }
      } else {
       alert("发生系统错误,请稍后重试");
     }
   }
  };
  xhr.send(null); // GET方式
}
//加载Main
function loadMain() {
require.config({
   baseUrl: './',
   urlArgs : 'v=' + APP_VERSION,
   waitSeconds: 0,
   paths: {
       'angular':'libs/angular/angular',
       'angular-ui-router': 'libs/angular-ui-router/angular-ui-router.min',
       'angular-async-loader': 'libs/angular-async-loader/angular-async-loader.min',
       'angular-css':'libs/angular-css/angular-css',
       'jquery': 'libs/jquery/jquery-3.1.0',
       'app':'config/app',
       'config':'config/config',
       'pageList':'config/pageList',
       'pageAttribute':'config/pageAttribute',
       'request':'services/request'
   },
   shim: {
       'angular-routes' : ['angular'],
       'angular': {exports: 'angular'},
       'angular-ui-router': {deps: ['angular']},
       "angular-css": ["angular"]
   }
   
});
}
//最先加载jquery
require(['jquery'], function() {
startLoad();
});
//启动app
function startLoad(){
// window.onerror = function(msg, url, line) {
// var idx = url.lastIndexOf("/");
// if (idx > -1) {
// url = url.substring(idx + 1);
// }
// alert("ERROR in " + url + " (line #" + line + "): " + msg);
// return false;
// };
require(['angular','app','config','angular-css','pageList','pageAttribute'],function(angular,app,config){
startApp();
})

function startApp() {
angular.bootstrap(document, ['app']);
       angular.element(document).find('html').addClass('ng-app');
}
}

三 、 App启动

define(['angular', 'angular-async-loader', 'module', 'angular-ui-router','angular-css'], function (angular, asyncLoader, module) {
    var app = angular.module('app', ['ui.router','door3.css']);
    asyncLoader.configure(app);
    module.exports = app;
});

四 、Config 配置文件

define(['pageAttribute','app'], function (pageAttribute,app) { 
//配置常亮

app.constant("errorMessage", "服务器异常,请稍后重试!");
app.constant("http", SERVER_URL);
    app.config(['$stateProvider', '$urlRouterProvider','$logProvider','$httpProvider', function ($stateProvider, $urlRouterProvider,$logProvider,$httpProvider,$rootScope) {
    //禁用ajax请求缓存
    if(!$httpProvider.defaults.headers.get){
    $httpProvider.defaults.headers.get = {};
    }
        //配置http发送模式
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
        delete $httpProvider.defaults.headers.common["X-Requested-With"];
        $httpProvider.defaults.headers.post["Content-Type"] = "application/json";
        
        $httpProvider.defaults.transformRequest = function(data){
        //当参数不为空的时候
        if(data){
        return JSON.stringify(data);
        }
        }
        
    $logProvider.debugEnabled(true);
    $urlRouterProvider.otherwise('/home');
   
    $urlRouterProvider.rule(function($injector, $location){
    var path = $location.path();
    normalized = path.toLowerCase();
    if (path !== normalized) {
            return normalized;
        }
    });
   
for (var k in pageAttribute) {
        pageAttribute[k].templateUrl;
        pageAttribute[k].controllerUrl;
        pageAttribute[k].css;
        $stateProvider.state(k, pageAttribute[k]);
   }

    }]);
    
    app.run(['$state', '$stateParams', '$rootScope', function ($state, $stateParams, $rootScope) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    }]);
    
    app.run(['$rootScope', '$log', function($rootScope, $log){
   
        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
        $rootScope.title = toState.data.pageTitle;
        });
        
        $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){
            $log.error('The request state was not found: ' + unfoundState);
        });
        
        $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
            $log.error('An error occurred while changing states: ' + error);
        });
        
        //通过$on为$rootScope添加路由事件
        
        $rootScope.$on('$routeChangeSuccess',function(event, current, previous){
            $log.debug('successfully changed routes');
        });
        
        $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
            $log.debug('error changing routes');
        });
        
    }]);
});


五 、 Services封装get、post请求

define(['app','config'],function(app,config){
var request = {};
app.service("request",function($http,http,errorMessage,$log){
  //GET请求
       this.get = function(url, params, success, error){
       
        if (typeof params == "function") {
      success = params;
      error = success;
      }
      
      url += "?" + urlEncode(params);
      
           $http.get(http + url ,{data:params}).success(function (resp) {
               success && success(resp);
           }).error(function (resp) {
                $log.debug(resp);
           });
       };
       //POST请求
       this.post = function(url, params, success, error){
          $http.post(http + url ,params).success(function(resp){
          success && successs(resp);
          }).error(function(resp){
          $log.debug(resp);
          })
       }
       //JS对象转URL参数
       function urlEncode(param, key) {
  var paramStr="";
  if(param instanceof String||param instanceof Number||param instanceof Boolean){
  paramStr+="&"+key+"="+encodeURIComponent(param);
  }else{
  $.each(param,function(i){
  var k=key==null?i:key+(param instanceof Array?"["+i+"]":"."+i);
  paramStr+='&'+urlEncode(this, k);
  });
  }
  return paramStr.substr(1);
  };
  // 
  //
  
  
})

return request;
}); 

六 、 controller文件

define(['app','request'],function (app,request) {

app.controller('home',function($state, $log, request){


request.get('',function(resp){

})

var Export = this;
        Export.title = "This is Home page";
        
        //页面跳转
        Export.home = function(){
        $location.path("home");
        };
        //启动路由
        Export.refresh = function(){
            $log.debug($state.current);
            $state.reload();
        }
   })   
});




七 、 页面问了参数化路由加载的时候通过pageAttribute文件加载页面,参数和title

define(function(){

var pageList = {};
var version = '?v='+APP_VERSION;

pageAttribute = {
home:{title:"单页面架构设计之HOME",parameter:{'customID':'001','productID':'110'}},
about:{title:"单页面架构设计之ABOUT",parameter:{'customID':'002','productID':'220'}},
message:{title:"单页面架构设计之MESSAGE",parameter:{'customID':'003','productID':'330'}}
}
//var attribute = pageAttribute[i];
for(var i in pageAttribute){
   pageList[i] = {
       url: '/'+i,
       templateUrl: 'view/'+i+'.html'+version,
       controllerUrl: 'controller/'+i+'.js'+version,
       controller: ''+i,
       css:'theme/css/'+i+'.css' +version,
       data : {
        pageTitle:pageAttribute[i].title,
        pageParameter:pageAttribute[i].parameter
       }
   }
   
}

return pageList;
});

 类似资料: