Home Web Front-end JS Tutorial AngularJs dynamically loads modules and dependencies

AngularJs dynamically loads modules and dependencies

Mar 25, 2017 pm 04:11 PM

I have been very busy with projects recently. I have to go to work during the day, and when I come back in the evening, I need to make a ppt of Angular knowledge points for my colleagues. After all, I am resigning at the end of the year, and someone still needs to take over the follow-up development of the project, so it takes up the time to study in the evening. . Originally I had not planned to write study notes on these third-party plug-ins, but I think it is indeed a benefit to load modules on demand and use them successfully, so I might as well record them. Since I haven’t used requireJs very deeply, I don’t know the difference between this and requireJs, and I can’t clearly explain whether this is Angular’s ​​on-demand loading.

In order to achieve the effect of the knowledge points of this study note, we need to use:

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

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

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

Without further ado, let’s get to the point ...

First let’s take a look at the file structure:

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             --- 主页面
Copy after login

Note: This demo does not do nested routing, but simply implements single-view routing to show the effect.

Let’s look at the code of the main page:

<!DOCTYPE html>
<html 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>
<p ng-app="templateApp">
  <p>
    <a href="#/default">主页</a>
    <a href="#/uibootstrap" >ui-bootstrap</a>
    <a href="#/ngtable">ng-table</a>
    <a href="#/ngtree">angular-tree-control</a>
  </p>
  <p ui-view></p>
</p>
</body>
</html>
Copy after login

On this page, we only loaded bootstrap’s css, angular’s ​​js, ui-router’s js, ocLazyLoad’s js, and 3 Configured js file.

Look at the html code of the four pages:

angular-tree-control effect page

<treecontrol tree-model="ngtree.treeData" class="tree-classic ng-cloak" options="ngtree.treeOptions">
   {{node.title}}
 </treecontrol>
Copy after login

There is an instruction corresponding to using the plug-in on the page.

default page

<p class="ng-cloak">
   {{default.value}}
 </p>
Copy after login

Here we just use it to prove that default.js is loaded and executed correctly.

ng-table effect page

<p class="ng-cloak">
  <p class="p-h-md p-v bg-white box-shadow pos-rlt">
    <h3 class="no-margin">ng-table</h3>
  </p>
  <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="&#39;Name&#39;" sortable="&#39;name&#39;">
        {{user.name}}
      </td>
      <td data-title="&#39;Age&#39;" sortable="&#39;age&#39;">
        {{user.age}}
      </td>
    </tr>
  </table>
</p>
Copy after login

Here are some simple ng-table effects.

ui-bootstrap effect page

<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>
Copy after login

Only a drop-down box effect is written here to prove that the plug-in is loaded and used correctly.

Okay, after reading the html, let’s take a look at the loading configuration and routing configuration:

"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.directive;
          tempApp.filter = $filterProvider.register;
          tempApp.factory = $provide.factory;
          tempApp.service =$provide.service;
          tempApp.constant = $provide.constant;
        }]);
Copy after login

The above code only relies on ui.router and oc.LazyLoad to register the module. The configuration is just a simple configuration of the module so that the subsequent js can recognize the methods on tempApp.

Then let’s look at the configuration of the ocLazyLoad loading module:

"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
  });
};
Copy after login

Routing configuration:

"use strict"
tempApp.config(["$stateProvider","$urlRouterProvider",routeFn]);
function routeFn($stateProvider,$urlRouterProvider){
  $urlRouterProvider.otherwise("/default");
  $stateProvider
  .state("default",{
    url:"/default",
    templateUrl:"views/default.html",
    controller:"defaultCtrl",
    controllerAs:"default",
    resolve:{
      deps:["$ocLazyLoad",function($ocLazyLoad){
        return $ocLazyLoad.load("js/controllers/default.js");
      }]
    } 
  })
  .state("uibootstrap",{
    url:"/uibootstrap",
    templateUrl:"views/ui-bootstrap.html",
    resolve:{
      deps:["$ocLazyLoad",function($ocLazyLoad){
        return $ocLazyLoad.load("ui.bootstrap");
      }]
    } 
  })
  .state("ngtable",{
    url:"/ngtable",
    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",
    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");
          }
        );
      }]
    } 
  })
};
Copy after login

The simple implementation of the ui-bootstrap drop-down box does not require a controller, then Let’s just look at the controller js of ng-table and angular-tree-control:

ng-table.js

(function(){
"use strict"
tempApp
.controller("ngTableCtrl",["$location","NgTableParams","$filter",ngTableCtrlFn]);
function ngTableCtrlFn($location,NgTableParams,$filter){
  //数据
  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 }];
  this.tableParams = new NgTableParams(  // 合并默认的配置和url参数
    angular.extend({
      page: 1,      // 第一页
      count: 10,     // 每页的数据量
      sorting: {
        name: &#39;asc&#39;   // 默认排序
      }
    },
    $location.search())
    ,{
      total: data.length, // 数据总数
      getData: function ($defer, params) {
        $location.search(params.url()); // 将参数放到url上,实现刷新页面不会跳回第一页和默认配置
        var orderedData = params.sorting ?
            $filter(&#39;orderBy&#39;)(data, params.orderBy()) :data;
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
      }
    }
  );
};
})();
Copy after login

angular-tree-control.js

(function(){
"use strict"
tempApp
.controller("ngTreeCtrl",ngTreeCtrlFn);
function ngTreeCtrlFn(){
  //树数据
  this.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:[]
            }
          ]
        }
      ];
  //树配置
  this.treeOptions = {
    nodeChildren:"childList",
    dirSelectable:false
  };
};
})();
Copy after login

Let us ignore default.js, after all there is only "Hello Wrold" in it.

For more articles related to AngularJs dynamic loading modules and dependencies, please pay attention to the PHP Chinese website!

Related articles:

AngularJS implements the method of dynamic compilation and adding to the dom

AngularJS dynamically generates the ID of the div

AngularJS implements the method of binding events to dynamically generated elements

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles