AngularJs動態載入模組和依賴注入簡單介紹

admin發表於2017-04-12

為了實現這篇學習筆記知識點的效果,我們需要用到:

angular: https://github.com/angular/angular.js。

ui-router: https://github.com/angular-ui/ui-router。

ocLazyLoad: https://github.com/ocombe/ocLazyLoad。

首先我們看下檔案結構:

[JavaScript] 純文字檢視 複製程式碼
Angular-ocLazyLoad                      --- demo資料夾
    Scripts                             --- 框架及外掛資料夾
        angular-1.4.7                   --- angular 不解釋
        angular-ui-router               --- uirouter 不解釋
        oclazyload                      --- ocLazyload 不解釋
        bootstrap                       --- bootstrap 不解釋
        angular-tree-control-master     --- angular-tree-control-master 不解釋
        ng-table                        --- ng-table 不解釋
        angular-bootstrap               --- angular-bootstrap 不解釋
    js                                  --- js資料夾 針對demo寫的js檔案
        controllers                     --- 頁面控制器資料夾
            angular-tree-control.js     --- angular-tree-control控制器程式碼
            default.js                  --- default控制器程式碼
            ng-table.js                 --- ng-table控制器程式碼
        app.config.js                   --- 模組註冊及配置程式碼
        oclazyload.config.js            --- 載入模組配置程式碼
        route.config.js                 --- 路由配置及載入程式碼
    views                               --- html頁面資料夾
        angular-tree-control.html       --- angular-tree-control外掛的效果頁面
        default.html                    --- default頁面
        ng-table.html                   --- ng-table外掛效果頁面
        ui-bootstrap.html               --- uibootstrap外掛效果頁面
    index.html                          --- 主頁面

注意:這個demo沒做巢狀路由,只是簡單實現單檢視的路由以展示效果。

我們來看主頁面的程式碼:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="Scripts/bootstrap/dist/css/bootstrap.min.css" />
    <script src="Scripts/angular-1.4.7/angular.js"></script>
    <script src="Scripts/angular-ui-router/release/angular-ui-router.min.js"></script>
    <script src="Scripts/oclazyload/dist/ocLazyLoad.min.js"></script>
    <script src="js/app.config.js"></script>
    <script src="js/oclazyload.config.js"></script>
    <script src="js/route.config.js"></script>
</head>
<body>
<div ng-app="templateApp">
    <div>
        <a href="#/default">主頁</a>
        <a href="#/uibootstrap" >ui-bootstrap</a>
        <a href="#/ngtable">ng-table</a>
        <a href="#/ngtree">angular-tree-control</a>
    </div>
    <div ui-view></div>
</div>
</body>
</html>

在這個頁面,我們只載入了bootstrap的css、angular的js、ui-router的js、ocLazyLoad的js,以及3個配置的js檔案。

再看看四個頁面的html程式碼:

angular-tree-control效果頁面

[HTML] 純文字檢視 複製程式碼
<treecontrol tree-model="ngtree.treeData" class="tree-classic ng-cloak" options="ngtree.treeOptions">
  {{node.title}}
</treecontrol>

頁面上有個使用該外掛對應的指令。

default頁面

[HTML] 純文字檢視 複製程式碼
<div class="ng-cloak">
  {{default.value}}
</div>

這裡我們只是用來證明載入並正確執行default.js。

ng-table效果頁面

[HTML] 純文字檢視 複製程式碼
<div class="ng-cloak">
  <div class="p-h-md p-v bg-white box-shadow pos-rlt">
    <h3 class="no-margin">ng-table</h3>
  </div>
  <button ng-click="ngtable.tableParams.sorting({})" class="btn btn-default pull-right">Clear sorting</button>
  <p>
    <strong>Sorting:</strong> {{ngtable.tableParams.sorting()|json}}
  </p>
  <table ng-table="ngtable.tableParams" class="table table-bordered table-striped">
    <tr ng-repeat="user in $data">
      <td data-title="'Name'" sortable="'name'">
        {{user.name}}
      </td>
      <td data-title="'Age'" sortable="'age'">
        {{user.age}}
      </td>
    </tr>
  </table>
</div>

這裡寫了些簡單的ng-table效果。

ui-bootstrap效果頁面

[HTML] 純文字檢視 複製程式碼
<span uib-dropdown class="ng-cloak">
  <a href id="simple-dropdown" uib-dropdown-toggle>
    下拉框觸發
  </a>
  <ul class="uib-dropdown-menu dropdown-menu" aria-labelledby="simple-dropdown">
    下拉框內容.這裡寫個效果證明實現動態載入即可
  </ul>
</span>

這裡僅寫了個下拉框效果,證明正確載入並使用該外掛。

好了,看完了html,我們看下 載入配置和路由配置 :

[JavaScript] 純文字檢視 複製程式碼
"use strict"
var tempApp = angular.module("templateApp",["ui.router","oc.lazyLoad"])
.config(["$provide","$compileProvider","$controllerProvider","$filterProvider",
                function($provide,$compileProvider,$controllerProvider,$filterProvider){
                    tempApp.controller = $controllerProvider.register;
                    tempApp.directive = $compileProvider.register;
                    tempApp.filter = $filterProvider.register;
                    tempApp.factory = $provide.factory;
                    tempApp.service  =$provide.service;
                    tempApp.constant = $provide.constant;
                }]);

以上程式碼對模組的註冊,僅僅依賴ui.router和oc.LazyLoad。

配置也只是簡單配置了模組,以便在後面的js能識別到tempApp上的方法。

然後我們再看看 ocLazyLoad載入模組的配置 :

[JavaScript] 純文字檢視 複製程式碼
"use strict"
tempApp
.constant("Modules_Config",[
    {
        name:"ngTable",
        module:true,
        files:[
            "Scripts/ng-table/dist/ng-table.min.css",
            "Scripts/ng-table/dist/ng-table.min.js"
        ]
    },
    {
        name:"ui.bootstrap",
        module:true,
        files:[
            "Scripts/angular-bootstrap/ui-bootstrap-tpls-0.14.3.min.js"
        ]
    },
    {
        name:"treeControl",
        module:true,
        files:[
            "Scripts/angular-tree-control-master/css/tree-control.css",
            "Scripts/angular-tree-control-master/css/tree-control-attribute.css",
            "Scripts/angular-tree-control-master/angular-tree-control.js"
        ]
    }
])
.config(["$ocLazyLoadProvider","Modules_Config",routeFn]);
function routeFn($ocLazyLoadProvider,Modules_Config){
    $ocLazyLoadProvider.config({
        debug:false,
        events:false,
        modules:Modules_Config
    });
};

路由的配置:

[JavaScript] 純文字檢視 複製程式碼
"use strict"
tempApp.config(["$stateProvider","$urlRouterProvider","$locationProvider",routeFn]);
function routeFn($stateProvider,$urlRouterProvider,$locationProvider){
    $urlRouterProvider.otherwise("/default");
    $stateProvider
    .state("default",{
        url:"/default",
        views:{
            "":{
                templateUrl:"views/default.html",
                controller:"defaultCtrl",
                controllerAs:"default"
            }
        },
        resolve:{
            deps:["$ocLazyLoad",function($ocLazyLoad){
                return $ocLazyLoad.load("js/controllers/default.js");
            }]
        } 
    })
    .state("uibootstrap",{
        url:"/uibootstrap",
        views:{
            "":{
                templateUrl:"views/ui-bootstrap.html"
            }
        },
        resolve:{
            deps:["$ocLazyLoad",function($ocLazyLoad){
                return $ocLazyLoad.load("ui.bootstrap");
            }]
        } 
    })
    .state("ngtable",{
        url:"/ngtable",
        views:{
            "":{
                templateUrl:"views/ng-table.html",
                controller:"ngTableCtrl",
                controllerAs:"ngtable"
            }
        },
        resolve:{
            deps:["$ocLazyLoad",function($ocLazyLoad){
                return $ocLazyLoad.load("ngTable").then(
                    function(){
                        return $ocLazyLoad.load("js/controllers/ng-table.js");
                    }
                );
            }]
        } 
    })
    .state("ngtree",{
        url:"/ngtree",
        views:{
            "":{
                templateUrl:"views/angular-tree-control.html",
                controller:"ngTreeCtrl",
                controllerAs:"ngtree"
            }
        },
        resolve:{
            deps:["$ocLazyLoad",function($ocLazyLoad){
                return $ocLazyLoad.load("treeControl").then(
                    function(){
                        return $ocLazyLoad.load("js/controllers/angular-tree-control.js");
                    }
                );
            }]
        } 
    })
};

ui-bootstrap的下拉框簡單的實現不需要控制器,那麼我們就只看看ng-table和angular-tree-control的控制器js吧:

ng-table.js

[JavaScript] 純文字檢視 複製程式碼
(function(){
"use strict"
tempApp
.controller("ngTableCtrl",["$location","NgTableParams","$filter",ngTableCtrlFn]);
function ngTableCtrlFn($location,NgTableParams,$filter){
    var vm = this;
    //資料
    var data = [{ name: "Moroni", age: 50 },
                 { name: "Tiancum ", age: 43 },
                 { name: "Jacob", age: 27 },
                 { name: "Nephi", age: 29 },
                 { name: "Enos", age: 34 },
                 { name: "Tiancum", age: 43 },
                 { name: "Jacob", age: 27 },
                 { name: "Nephi", age: 29 },
                 { name: "Enos", age: 34 },
                 { name: "Tiancum", age: 43 },
                 { name: "Jacob", age: 27 },
                 { name: "Nephi", age: 29 },
                 { name: "Enos", age: 34 },
                 { name: "Tiancum", age: 43 },
                 { name: "Jacob", age: 27 },
                 { name: "Nephi", age: 29 },
                 { name: "Enos", age: 34 }];
    vm.tableParams = new NgTableParams(    // 合併預設的配置和url引數
        angular.extend({
            page: 1,            // 第一頁
            count: 10,          // 每頁的資料量
           sorting: {
                name: 'asc'     // 預設排序
            }
        },
        $location.search())
        ,{
            total: data.length, // 資料總數
            getData: function ($defer, params) {
                $location.search(params.url()); // 將引數放到url上,實現重新整理頁面不會跳回第一頁和預設配置
                var orderedData = params.sorting ?
                        $filter('orderBy')(data, params.orderBy()) :data;
                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
            }
        }
    );
};
})();

angular-tree-control.js

[JavaScript] 純文字檢視 複製程式碼
(function(){
"use strict"
tempApp
.controller("ngTreeCtrl",ngTreeCtrlFn);
function ngTreeCtrlFn(){
    var vm = this;
    //樹資料
    vm.treeData = [
                {
                    id:"1",
                    title:"標籤1",
                    childList:[
                        {
                            id:"1-1",
                            title:"子級1",
                            childList:[
                                {
                                    id:"1-1-1",
                                    title:"再子級1",
                                    childList:[]
                                }
                            ]
                        },
                        {
                            id:"1-2",
                            title:"子級2",
                            childList:[
                                {
                                    id:"1-2-1",
                                    title:"再子級2",
                                    childList:[
                                        {
                                            id:"1-2-1-1",
                                            title:"再再子級1",
                                            childList:[]
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            id:"1-3",
                            title:"子級3",
                            childList:[]
                        }
                    ]
                },
                {
                    id:"2",
                    title:"標籤2",
                    childList:[
                        {
                            id:"2-1",
                            title:"子級1",
                            childList:[]
                        },
                        {
                            id:"2-2",
                            title:"子級2",
                            childList:[]
                        },
                        {
                            id:"2-3",
                            title:"子級3",
                            childList:[]
                        }
                    ]}
                ,
                {
                    id:"3",
                    title:"標籤3",
                    childList:[
                        {
                            id:"3-1",
                            title:"子級1",
                            childList:[]
                        },
                        {
                            id:"3-2",
                            title:"子級2",
                            childList:[]
                        },
                        {
                            id:"3-3",
                            title:"子級3",
                            childList:[]
                        }
                    ]
                }
            ];
    //樹配置
    vm.treeOptions = {
      nodeChildren:"childList",
        dirSelectable:false
    };
};
})();

相關文章