English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
AngularJS has several major features, such as:
1 MVC
2 Modularization
3 Directive system
4 Two-way data binding
So let's take a look at the modularization of AngularJS in this article.
Firstly, let's talk about why we need to implement modularization:
1 Increased the reusability of modules
2 By defining modules, we can customize the loading order
3 In unit tests, there is no need to load all the content
In previous examples, the controller code was written directly inside the script tag, and the functions declared in this way are global, which is obviously not the best choice.
Let's see how to modularize:
<script type="text/javascript"> var myAppModule = angular.module('myApp', []); myAppModule.filter('test', function(){ return function(name){ return 'hello, '+name+'!'; }; }); myAppModule.controller('myAppCtrl', ['$scope', function($scope){ $scope.name='xingoo'; }); </script>
Firstly, create the module myAppModule through the global variable angular.
angular.module('myApp',[]);
The first parameter is the bound application name app, which identifies the entry point of angular in the page, similar to the role of the main function.
The second parameter [] identifies the modules that are dependent.
Let's see how to use modules!
!doctype html <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body> <div ng-controller="myAppCtrl"> {{name | test }} </div> <script type="text/javascript"> var myAppModule = angular.module('myApp', []); myAppModule.filter('test', function(){ return function(name){ return 'hello, '+name+'!'; }; }); myAppModule.controller('myAppCtrl', ['$scope', function($scope){ $scope.name='xingoo'; }); </script> </body> </html>
Directly bind myApp to ng-It's enough on app.
In the script, we create a filter and a controller through the module.
The role of filter is to add string decoration.
The role of the controller is to initialize variables.
The running result of the program is as follows:
This is the material collection of AngularJS Modularization. We will continue to supplement relevant materials in the future, thank you all for your support to this site!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)