Module-Basic AngularJS tutorial
0. Directory
Contents Preface body 1 Why use Angular modules Why use modular 2 create application module-Creating the application module 3 load application module-Loading the application module 4 define controller-Defining a controller 5 chain definition- chaining definitions 6 Loading module-Loading modules 7 conclusion
1. Preface
AngularJS is designed to overcome the shortcomings of HTML in building applications. HTML is a well-designed declarative language for static text display, but it seems weak to build WEB applications, angularJS has done some work to solve the shortcomings of static Web Page Technology in building dynamic applications.
AngularJS was originally designedSimplify web APP development, The essence isSimple. However, there are many AngularJS tutorials at home and abroad, all focusing on the strengths of AngularJS, which increases the difficulty of AngularJS learning. This tutorial attempts to explain in a popular language.Basic,Most practicalContent,Simplify the learning process and reduce the learning difficultyIs the original intention of this tutorial.
This series of tutorialsTranslationChris SmithOfAngualr BasicsTo provide you with a brief overview, integrate the understanding of the bloggers.Simple and clear.
This article is a series of tutorial 7th modules, translated fromModules.
Preface-Introduction Basics-Basics controller-Controllers scope-Scopes set-Collections
Module-ModulesDependency Injection-Dependency Injection service-Services filter-Filters command-Directives command scope-Directive Scopes route-Routing communication-HTTP conclusion 2. Body
In general, modules are designed to be visualized by defining public APIs, limiting behaviors (functions), and data (attributes and variables ).Separation of concerns(Separation of concerns, soc ). Most programming platforms have built-in support for modularity, so that we will naturally feel imperceptible. However, javascript on the client side is not supported, and the advantages and disadvantages of additional solutions (such as CommonJS and AMD) are also discussed.
It should be noted that Angular's modular system is not modularized (it does not load source code from files or the internet ), angular provides a built-in, private modular solution that works in a similar way to its built-in, private dependency injection solution. The two systems provide impressive general infrastructure. Although the use of modular functions is essential for every developer, the question is, why do we need them?
Although modularity and dependency injection are usuallyRequiredProposition, but Angular allows us not to use modules to implement many things. So far, we have completed a series of cases of using Constructors (defining functions with the same name as controllers in a global scope) without modules. With a simple setup, the ng-controller command looks for controller functions in a global range and modular system, allowing us to use Angular in a simplified way, but to a certain extent.
2.1 Why use Angular modules? (Why use modularity)
In order for us to go further after Angular's basic features, we need to be proficient in its modular system. Compared to the management complexity of JS objects, we should use a simple method to solve the problem and find your own best practices. Therefore, this book does not want to detail the essential features of modularity and dependency injection, this section only describes the modules and dependency injection that are closely related to Angular usage.
Therefore, let's take a look at the important features that must use the Angular module:
Special components-Specialized componentsWhen defining your own controllers, commands, filters, and animations, we must use the module system (the Controller may be an exception, as mentioned earlier)
Dependency injection-Dependency injectionAlthough the service is a common JS object and function, the Service created using the module system can be simply injected with dependency.
External module-External modulesAngular has a very attractive development community, a massive number of free official plug-ins, third-party plug-ins, if you want to use these libraries in your application, we have to use the module system.
Load-time configurationAngular's module system provides the ability to access internal configurations and plug-in configurations.
Configure custom HTTP headersThe following feature is demonstrated in the example.
Test-TestingAngular's exciting test functions are implemented based on dependency injection, which is also inseparable from the module system.
In the next chapter, we will describe services to demonstrate how to provide support for custom JS Component definitions. This chapter explains how to define a controller to load external modules and explains the basis of the module system.
2.2 create an application module-Creating the application module
An Angular application usually starts with a root module. In our case, this module is called app,Note:Although this name is common, it may not be the best choice for simplicity.
/* module.js */angular.module('app', []);
In the above case, pay special attentionModuleAlthough it looks like an empty array, it is very important. If you ignore it,angular.moduleWill have a fundamental change. Considering the rational design of the API, When you specify the second parameter to call angular. module, this method is in creation mode. If the module named app does not exist, a module named app will be created. Howeverangular.moduleWhen the second parameter is not specified, it is in the search mode. If the module with the given name exists, this module will be returned. If the module does not exist, an error will be thrown, reminding us to pay attention to the second parameter. In this case, we use the correct method, but we need to understand the important differences in the code. This parameter is used to import external modules. We will explain this in the case of angular animation module.
2.3 load the application module-Loading the application module
In the HTML document that carries the application, we need to pass the module name as a parameterng-appThe Command tells Angular to load the application module.
Any component we add to the application module can be used. Let's see how to use the module to define a controller (not using the global scope ).
2.4 define controller-Defining a controller
moduleThe API contains some methods for defining special Angular components.controllerMethod, we usecontrollerMethod To create a controller. First, we need to get an application module reference. At the same time, we needangular.moduleLeave the second parameter unspecified to make it in the query mode (mainly because we have already created an application module ).
/* message-controller.js */var app = angular.module('app');app.controller('MessageController', function($scope) { $scope.message = "This is a model.";});
Then we need to callng-appTo a location in the element, useng-controllerCall our controller.
{{message}}
The compilation result is: This is a model.
As you can see, using a module-defined controller is a little more difficult than using a global scope, but it is not too bad.
2.5 chain definition-Chaining definitions
Suppose we need to define the following two controllers
{{message}}
{{message}}
moduleYou can use a chain operation to define two controllers in a statement.
/* chained-controllers.js */angular.module('app') .controller('MessageController', function($scope) { $scope.message = "This is a model."; }) .controller('AnotherMessageController', function($scope) { $scope.message = "This is another model."; });
The compilation result is:
This is a model.
This is another model.
Note:The statement of the first controller does not end with a semicolon.
If you do not like the chained operation style, you can retrieve the call module at any time, or store it in a variable (as shown in the code below ). If you use variables, it is best to avoid global variables contamination in IIFE (call function expressions immediately) or other closures.
/* separate-controllers.js */var app = angular.module('app');app.controller('MessageController', function($scope) { $scope.message = "This is a model.";});app.controller('AnotherMessageController', function($scope) { $scope.message = "This is another model.";});
You can decide which style to choose, but the chain style is more popular.
2.6 load module-Loading modules
AnimationIs a new feature of Angular calledngAnimateIndependent module. The first step to use animations is to introduce the inclusion module. The source file is the core part of Angular, but it is distributed by a separate file during distribution, as shown below.
<Script src = "// ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"> </script> <script src = "// repository"> </script>
<Script src = "// cdn.bootcss.com/angular.js/1.3.14/angular.js"> </script> <scriptsrc = "// regular"> </script>
It is time to use the second array parameter of the module method. In the previous case, we only passed an empty parameter. This time, we declare the module dependency.
/* ng-animate-module.js */angular.module('app', ['ngAnimate']);
In this way, ngAnimate is introduced in the application. The ng-show, ng-hide, and ng-class commands in the template will detect js animation in css and JS, it may be applied to DOM events such as add, enter, leave, move, and remove. Apply animation in DOM events without making any changes to the template (it feels as transparent). If the animation code is not rendered, either as css or as js through[module.animation](http://docs.angularjs.cn/api/ng/type/angular.Module)Registration, command code or common code.
Check the box to show the message
The secret message.
The compilation result is:
Click the check box above to see that the display and hiding between elements are performed immediately, because we did not add animations in css or js. Next, we will use css (a good choice for creating general animations through declarative styles). Of course, jQuery's animate method is also good, and Angular module. animation can be compatible with these methods. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPr/placement = "brush: java;"> /* ng-animate.css */.ng-hide-add,.ng-hide-remove { transition: all linear 1s; display: block !important;}.ng-hide-add.ng-hide-add-active,.ng-hide-remove { opacity: 0;}.ng-hide-add,.ng-hide-remove.ng-hide-remove-active { opacity: 1;}
The compilation result is as follows.
Depending on the user needs of your website, you may need to add a browser engine prefix (vendor-prefix) to a specific css attribute ), for example, added-webkit-transition for iOS Safari6 (caniuse.com is a good html5 and css3 browser compatibility website ). Note that this animation will be appended to any ng-show or ng-hide usage. For better control, we can add custom css classes on elements and selectors, such.my-class.ng-hide-addAnd.my-class.ng-hide-removeAnd so on.
2.7 conclusion
AddngAnimateI want to convince you of the importance of the Angular module system. And, happily,ngAnimateIn addition to official module resources, you can also find more third-party open-source modules on websites such as github. The most popular project is AngularUI, which provides powerful modules such as UI Router and UI Bootstrap. These modules can be conveniently installed using Bower. After you get started with Angular, you can also release your Angular module on Github and Bower!
ngAnimateThe module demonstrates how to use the attachment module to exert its powerful functions. However, because of its special embedding method, dependency injection is not used. Because modules and dependency injection need to collaborate with each other, we will explain dependency injection in the next chapter.