AngularJS entry case
Recently, the company is engaged in new projects. The web end adopts angularJS. I will not explain much about what angularJS is and its basic usage here, because if you want to write it later, A little bit further, new people will be confused by some of its concepts when they come into contact with ng. I just got in touch with some of ng's concepts for a few days before I figured out the relationship between them, I may say something wrong here. Please forgive me and correct me. This article uses an actual case to explain the relationship among modules, controllers, services, and commands and complete a login function.
First of all, angularJS is a front-end framework based on MVC. MVC is the concept of controllers, views, and data models. When we use struts, the data model is actually the javabean or field defined in the action, the view is jsp or html, and the Controller is our action, so that they perform their respective duties to complete MVC, similarly, angularJS also implements MVC decomposition, which is a big difference from jquery, but I don't think jquery has no MVC, however, we do not have similar development habits during normal development. jquery does not provide such a development mode, so we ignore it. angular provides these natural support. In angularJS, the controller is used to obtain basic information, jump, call, and so on. In the controller, we operate the model and operate the model to operate the scope, the so-called scope I understand is an object used to store data, just like the request object session object that struts uses, and the applcation object is equal to the rootScope object in angular. A view is html. in html, we will introduce some common components such as forms, lists, and drop-down boxes. We usually use easyui for these ui components. In angular, we will use commands for encapsulation. Of course, angular provides some built-in commands.
In this case, there is still a bit of chaos. Simply put, the user can see the view using commands and pass the data parameters to the Controller through the operation commands. After the Controller obtains the relevant parameters from the scope, call the service to complete the specific business logic.
There are two other concepts: 1 is a module and 2 is a service. A module is a package that encapsulates a specific type of operations (commands, controllers, and services. When we want to use a command or controller, we only need to introduce this module (package. Of course, the definition of a module not only needs to include these things, but it can contain commands, controllers, or services, such
// Define the relevant Module window. routeModule = angular. module ('msd. routes ', ['ngroute']); window. serviceModule = angular. module ('msd. services ', ['ngresource']); window. controllerModule = angular. module ('msd. controllers ', ['msd. services ']); window. diretiveModule = angular. module ('msd. direves ves ', ['msd. services ', 'msd. controllers ']); window. filterModule = angular. module ('msd. filters ', []); window. cookieModule = angular. module ('msd. cookies ', ['ngcookies']);
We will not discuss how they are best defined, but look at the specific project implementation. Dependencies and injection can be performed between these modules. For example, in window. diretiveModule = angular. module ('msd. direves ves ', ['msd. services ', 'msd. controllers ']); To inject service and controller into the command module. In this way, all commands can call controllers and service-related interfaces. A service is simply a function or an interface that helps us process some business logic. It can also be understood as a tool, because angular provides many ready-made services, such as the most commonly used $ http service. Through $ http, we can use post and get requests.
The above are some basic knowledge. Let's talk about the details later. Here is a logon demo.
First, we need to introduce some angular lib, because our demo is very simple, so we introduced a js:
<script type="text/javascript" src="../../../lib/angular/angular.js"></script>
In addition, we will classify other js Code into other JS files, so we should also remember to introduce it (we may use requirJS in actual development) this is not so complicated.
<script type="text/javascript" src="../controller/controller.js" ></script><script type="text/javascript" src="../directive/directive.js" ></script><script type="text/javascript" src="../service/loginService.js" ></script>
From the introduction, we can see that we have decomposed the controllers, commands, and services, which makes maintenance easy. The entire directory structure is as follows:
First, let's look at the login.html file: the page is very simple. Apart from some js files introduced, we only write a line of instruction code, and this plus-user-form is a custom instruction, it is a ui component.
<Script type = "text/javascript" src = ".. /.. /.. /lib/angular. js "> </script> <script type =" text/javascript "src = ".. /controller. js "> </script> <script type =" text/javascript "src = ".. /directive. js "> </script> <script type =" text/javascript "src = ".. /service/loginService. js "> </script>
On the page, we also need to note that in the second row, we have written an ng-app attribute with the value of myApp, and angular uses ng-app as the entry, once it finds that ng-app exists, it considers all the pages under it to be managed by angularJS. We assigned myApp to ng-app, which means that the ui and business logic processing of this page belong to the myApp module. As I mentioned earlier, since myapp is a module, it is similar to a package, which contains controllers and services. Similarly, we can also find the command we defined. Next we will look at the definition of a module, open the controller, js file, we can see this line of code:
Var myApp = angular. module ('myapp', []); // This line of code uses the module method provided by angular to create a module named myApp. [] should be a dependent module or service.
In this module, we first create a controller. The code for creating a controller is as follows, which is also in the controller. js file:
MyApp. controller ("loginController", function ($ scope, $ location, $ window, LoginService) {$ scope. login = function () {if (! $ Scope. username) {console. log ("Enter the user name"); return;} if (! $ Scope. password) {console. log ("Enter Password"); return;} LoginService. loginDo ({'username': $ scope. username, 'Password': $ scope. password }). then (function (data) {if (data = null) {console. log ("Logon exception");} else {if (200 = data) {console. log ("Logon successful"); $ window. location. href = "http://www.baidu.com";} else {console. log ("failed"); $ window. location. href = "http://www.damai.cn ";}}});};});
We created a controller named loginController through the controller method. This controller is a function that injects $ scope, $ location, $ window, and other built-in services, in addition, we have injected the LoginService our custom service. Why can we introduce this LoginSerivce here? Because this LoginService also belongs to this module. this service is created in the js file. Next, we create a login function for $ scope, which can be called just like the interface in action. Similarly, it can also define some attributes. For example, $ scope. username is the attribute created in scope. We can determine whether it is empty by obtaining the user name and password. If it is empty, we will prompt you (angularJS provides a lot of verification mechanisms and prompts, which we will not elaborate on here ). If the username and password are not empty, we call the loginDo function of loginService to pass the username and password. In loginDo, the $ http service is actually called to request the background. When $ http is called, a promise object is returned, which has a then method for processing callback. The data parameter in the then method represents the response data of this request. In addition, success () and error functions are provided. Here we make a simple judgment. If the server returns 200, we will jump to Baidu. If not, we will jump to damai.com. In this way, our controller is complete. Is it similar to the action in struts? Let's take a look at how loginService is defined and open the LoginService. js file. The Code is as follows:
var myApp = angular.module('myApp');myApp.factory("LoginService",function($http,$q){return {loginDo: function(httpParams){var deferred = $q.defer();$http({method:"post",url: "/angular-war/loginServlet",params:httpParams}).success(function(data, status) {deferred.resolve(data);}).error(function(data, status) {deferred.reject(null);});return deferred.promise;}};});
First, we obtain the module myapp through the module method, and create a service named LoginService using the factory method provided by angular (there are many ways to create a service, such as service (), provider () we will not elaborate on their differences here.) The $ http service and $ q service are introduced to this service. We are familiar with http and I am not familiar with $ q service, I used it in our project, Baidu.
You can call $ q. defer () to create a new deffered instance. The deffered object is used to associate a Promise instance with an API that marks the task status (successful or failed. Deffered object method resolve (value) -- pass in value to solve the derived promise. If value is a rejection object constructed by $ q. reject, the promise will be rejected. Reject (reason) -- reject the derived promise and provide the reason. This is equivalent to passing a denial object (rejection) constructed by $ q. reject as a parameter to resolve. Y (value) -- provides status updates during promise execution. This may be called multiple times before promise is resolved or rejected.
Let's talk about it first. Then we call the server interface through the post or get method and return the result to the Controller.
OK, we have read the controller and service, and the module also knows what is going on. We have also read the page, and there are the remaining commands. The directive direve ve just said, it can be understood as a UI component. angularJS provides some built-in commands, but also provides APIs for custom commands, in this way, people around the world can encapsulate excellent commands for everyone to use. Here we just wrote it for demonstration, and opened the direcitve. js file. The Code is as follows:
var myApp = angular.module("myApp");myApp.directive('plusUserForm', function () {return {restrict: "E",replace: true,templateUrl: '/angular-war/resource/js/login/html/plusUserForm.html'};});
What are the meanings of custom commands and command-related attribute functions? It can be discussed as a topic, here we just briefly talk about the form in which the restrict code command is displayed on the page in four formats: E (element) element A (attribute) attribute C (class) class M (comment) where the property is the default, because the property has the best compatibility. Replace indicates whether the template returned by the "false" or "true" code is nested in the command or overwrite the command. templateUrl indicates the specific UI page of the command. Here we use the html of plusUserForm. Next, let's refer to this formform. The code for opening the plususerform.html file is as follows:
Several Notes in this form include the ng-controller command for using angularJS content. It indicates that this form will be submitted to this controller for processing after it is submitted, we have defined this loginController. In the two text boxes, the ng-model command binds two attributes: username and password, which correspond one to one in the scope of the controller. Finally, we use the ng-click command in the tag, which means that once we click the hyperlink, the login function will be triggered. This login function is defined in the loginController.
Okay, so we will go through the whole process. Finally, let's take a look at how to write the background code. To help me write a servlet, the Code is as follows:
public class LoginServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {try {String username = req.getParameter("username");String password = req.getParameter("password");System.out.println("username:"+username+",password:"+password);PrintWriter printWriter = resp.getWriter();printWriter.print(200);printWriter.flush();printWriter.close();} catch (Exception e) {e.printStackTrace();}}}
After all the code is finished, let's take a look at the effect and go to the homepage.
Enter the user name and password, and click Login. The page is redirected to the baidu page, so that our demo is complete.
If I have time, I will sort out other related knowledge and share it with you.