Angular JS + Require JS 實現按需加載

先看下目錄結構,爲了方便配置將全部文件放在同一文件夾下,實際使用過程當中建議歸類文件:javascript

1.index.htmlcss

<!DOCTYPE html>
 
<html lang="en">
 
<head>
 
  <meta charset="UTF-8">
 
  <title>require angularjs</title>
 
</head>
 
<body>
 
<a href="#module1" rel="external nofollow" >module1</a><br/>
 
<a href="#module2" rel="external nofollow" >module2</a>
 
<div style="height: 30px;width: 100px">{{str}}</div>
 
<div id="container" ui-view></div>
 
<script data-main="main.js" src="require.js" id="main"></script>
 
</body>
 
</html> 

2.main.jshtml

var config = {
 
  baseUrl: './',      //依賴相對路徑
 
  paths: {          //若是某個前綴的依賴不是按照baseUrl拼接這麼簡單,就須要在這裏指出
 
 
    angular: 'angular',
 
    app:'app',
 
    router:'angular-ui-router'
 
  },
 
  shim: {           //引入沒有使用requirejs模塊寫法的類庫。例如underscore這個類庫,原本會有一個全局變量'_'。這裏shim等於快速定義一個模塊,把原來的全局變量'_'封裝在局部,並導出爲一個exports,變成跟普通requirejs模塊同樣
 
    'router': {
 
      deps: ['angular'],  //依賴什麼模塊
 
        
 
    },
 
    'angular': {
 
      exports: 'angular'
 
    }
 
  }
 
};
 
require.config(config);
 
// deps:['webapp']
 
require(['app','angular'],function(){
 
  angular.bootstrap(document, ['webapp'])//這裏會去執行app.js這個文件
 
}) 

3.app.jsjava

define(['router'], function () {
 
  var app = angular.module('webapp', ['ui.router']);
 
  app.config(
 
    function($stateProvider, $urlRouterProvider) {
 
      $urlRouterProvider.otherwise('module1');
 
      $stateProvider.
 
      state('module1', {
 
        url:"/module1",
 
        // controller: 'ctr1',     
 
        templateUrl: './module1.html',
 
        resolve: {
 
          loadCtrl: ["$q", function($q) {
 
            var deferred = $q.defer();

 
            require([
 
              './module1'
 
            ], function() { deferred.resolve(); });
 
            return deferred.promise;
 
          }]
 
        }
 
      })
 
      .state("module2",{
 
        url:"/module2",
 
        // controller: 'ctr2',
 
        templateUrl: './module2.html',
 
        resolve: {
 
          loadCtrl: ["$q", function($q) {
 
            var deferred = $q.defer();
 
         
            require([
 
              './module2'
 
            ], function() { deferred.resolve(); });
 
            return deferred.promise;
 
          }]
 
        }
 
      })
 
    });
 
  app.config(function($controllerProvider,$compileProvider,$filterProvider,$provide){
 
    app.register = {
 

 
      controller : $controllerProvider.register,
 
   
      directive: $compileProvider.directive,
 
      filter: $compileProvider.register,
 
      service: $provide.service
 
    };
 
  })
 
  return app;
 
}); 

4.module1.htmlnode

<div ng-controller="ctr1">

5.module2.htmlangularjs

<div ng-controller="ctr2">
  {{str}}
</div> 

6.module1.jsweb

define(['app'],function(app){
 
  app.register
 
    .controller('ctr1', function($scope){
 
      $scope.str = 'home page';
 
      console.log('page1')
 
    })
 
}) 

7.module2.jsbootstrap

define(['app'],function(app){
 
  app.register
 
    .controller('ctr2',function($scope){
 
      $scope.str = 'local page';
 
      console.log('page2')
 
    })
 
}) 

8.server.js  (node 服務)promise

var url  = require("url"),
    fs=require("fs"),
    http=require("http"),
    path = require("path");

http.createServer(function (req, res) {
    var pathname=__dirname+url.parse(req.url).pathname;
    if (path.extname(pathname)=="") {
        pathname+="/";
    }
    if (pathname.charAt(pathname.length-1)=="/"){
        pathname+="index.html";
    }

    fs.exists(pathname,function(exists){
        if(exists){
            switch(path.extname(pathname)){
                case ".html":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".js":
                    res.writeHead(200, {"Content-Type": "text/javascript"});
                    break;
                case ".css":
                    res.writeHead(200, {"Content-Type": "text/css"});
                    break;
                case ".gif":
                    res.writeHead(200, {"Content-Type": "image/gif"});
                    break;
                case ".jpg":
                    res.writeHead(200, {"Content-Type": "image/jpeg"});
                    break;
                case ".png":
                    res.writeHead(200, {"Content-Type": "image/png"});
                    break;
                default:
                    res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }

            fs.readFile(pathname,function (err,data){
                res.end(data);
            });
        } else {
            res.writeHead(404, {"Content-Type": "text/html"});
            res.end("<h1>404 Not Found</h1>");
        }
    });
}).listen(5000);
console.log("Server running at localhost");

參考地址:https://www.jb51.net/article/115695.htmapp

相關文章
相關標籤/搜索