first, Preface
The development of the front-end technology is so fast, a variety of excellent technology, excellent framework of the emergence of simply dizzying, as an industry rookie, keep up with the trend of the times, learning to master new knowledge is naturally not to neglect. When you hear the name of Angularjs and know that Google is in the maintenance of it, it has been concerned about, see that it is very hot abroad, but the domestic use of the situation there is no small gap, the reference Literature/network article is also very scarce. long-awaited, decided to study angular, and write a series of blogs, on the one hand as their learning path on the record, on the other hand also to interested students some REFERENCE.
First of all, I am a learner, will be the perspective of the learner to organize my ideas, so the series of blog can not be called a tutorial, can only be some exploration, understanding or technical errors also please point Out. second, I especially like to write a small example to make a clear, so in the text as much as possible with the example code to explain, I believe this will be a good way. finally, I know that under the existing conditions for angular learning will be difficult, but I believe that the strength of perseverance, so I would like to use this text as a driving force for future learning, let us come into the angular world it ~
second, What is Angularjs
This definition must be dingzhun, and AngularJs (which is referred to as NG Later) is a structural framework for designing Dynamic Web Applications. first, It is a framework, not a class library, that provides a complete set of scenarios like backbone for designing web Applications. It is not just a JavaScript framework, because its core is actually the enhancement of HTML tags, there is a picture of the truth, please crossing network description:
What is HTML tag enhancement? In fact, you can use the label to complete part of the page logic, the way is through custom tags, custom attributes, and so on, these HTML raw tags/attributes have a name in ng: Directive (directive). Details will be presented Later. So what is Dynamic Web application? Unlike traditional Web systems, Web applications can provide users with a rich range of operations that can be continuously updated with user actions without URL jumps. Ng has also declared that it is more suitable for developing crud applications, which are more applications for data manipulation than for games or image processing Applications.
To achieve this, Ng introduces some very good features, including template mechanics, data binding, modules, directives, dependency injection, and Routing. The binding of the data to the template allows us to get rid of the tedious DOM operations and focus our attention on the business Logic. These I will study in the later one by one Studies.
Another question, ng is the MVC framework? or the MVVM framework? The website mentions that Ng's design uses the basic idea of mvc, not exactly mvc, because we do use the Ng-controller directive (at least from the name, Mvc) when writing Code. But the Controller's business is basically interacting with the view, so it looks very close to Mvvm. Let's move to the non-prominent title on the official website: "angularjs-superheroic JavaScript MVW Framework".
All right, MVW. W-whatever. Whatever is the MV what good, so also someone wrote in order to mv*. Actually tangled this also really not necessary, and so on in the future to the whole frame familiar, in which the structure naturally clear in the Heart.
third, Start running angular
With an approximate hazy understanding, I believe many of the concepts will be clear in the process of use. I can't wait to get angular up and running. Hands on ~
First from the official website Http://angularjs.org/download angular.js, introduce your page, and then we use the simplest manual startup method, call the Bootstrap method directly. All the code is as Follows:
<! DOCTYPE html>
Only one line of Code. Call the bootstrap method to pass in the scope and initialize the module array (null here). is not very simple. You will soon see a more special one here:
<div> 1+1={{1+1}}</div>
If you have used other template libraries, you should be familiar with this notation, {{}} double curly braces, which is the markup used to write the expression in Ng's template, and after Ng is successfully run, the expression in {{}} will take effect, that is, the page will appear as Follows:
In order not to let you see ng so simple, I must tell you generally do not start, to see a slightly modified code:
<! DOCTYPE html>
One more attribute on the
Iv. binding of templates to datafirst, you need to clarify the concept of the Template. When I do not know that there is a template this thing, have used JS splicing a long HTML string, and then append to the page, this way to think is really dirt and stupid. Later I saw that I could wrap the HTML code in a <script> tag as a template and then use it as Needed. In ng, the template is very simple, it is the HTML code on our page, no need to attach anything Extra. You can use a variety of instructions in the template to enhance its functionality, which allows you to skillfully bind the template and Data.
Binding this thing is a big contributor in Ng. When we use jquery, the code is flooded with statements like this: var v = $ (' #id '). val (); $ (' #id '). HTML (str), that is, frequent DOM operations (read and write), in fact, our ultimate goal is not to manipulate the dom, But to implement business Logic. Ng's bindings will let you get rid of Dom operations, as long as the template and the data are bound by the declaration, the two will be kept in sync, the latest data will be displayed in real time in the page, the page user modified data will be recorded in the data model in real Time.
I have conceived a small example, and the example in this article will revolve around this small example. I guess you're tired of the login module or the shopping cart example, let's try something new. I have become a teacher, I want to use a Web application to give students an online Question. Let's start with a Question.
<! DOCTYPE html>There are two input boxes on the page that represent the topic and score, and a live preview area below to show the final output of the Topic. Ng-controller= "textc" is used to declare a template area that needs to be bound to the data, its scope is within the div, and the name is TEXTC,JS code that defines a function named TEXTC corresponding to it, we will complete the binding within this Function. The function passes in a parameter $scope, which indicates the scope of the Action. We assign values to four variables for newtitle, previewtitle, name, fraction, respectively, within the scope of the Action. The {{}} in the
Only one-way binding of data to a template can be done through {{}}. For two-way binding, we need to use the Ng-modle directive, which we use to bind the topic and the score in two directions, so that when the value in the input box changes, the variable in the function will follow the change, and its changes will be fed back in the preview area BELOW. Because there is also a binding for name and fraction in the preview Area.
Try editing in the input box below.
We do not do any DOM operations, and the framework automatically completes the Dom's values and Assignments. In the following I will continue to refine this example and introduce more new Concepts.
V. Some control modes in the templateWhen we use other template libraries, we generally have similar controls like Loop output, branch output, logical judgment, and so On. What controls are available in the NG template? to explore it.
1. Cyclic OUTPUTContinue with the above Example. Questions and scores are not enough, I want a choice problem, you can add several options and edit the contents of the options, how to write the code? First on the Code:
HTML section:
<div ng-controller= "testc" > JS Section:
var app = Angular.module (' MyApp ', [], function () {console.log (' started ')}), var questionmodel = { newtitle: ' new question ', C7/>previewtitle: ' Preview question ', name: ', fraction: ', options: []};app.controller (' testc ', function ($scope ) { $scope. question = questionmodel; $scope. addoption = function () { var o = {content: '}; $scope. Question.options.push (o); }; $scope. deloption = function (index) { $scope. question.options.splice (index,1);}; });
Please note that my JS code has a little change, in the data binding is not directly written as a string, but all the data is written into a Questionmodel object, this is a universal JS object, so that our data can look like "model", after all, we are mv*. So in the template, we use the name of the place also changed to question.name, the other values also the Same. In the controller section, I did not use var textc = function () {} as such, but instead changed to App.controller (' textc ', function () {}), This explicitly specifies that the controller belongs to the MyApp module, and our mv* code looks more professional and Integrated.
In the HTML section I added a list in the new and preview areas to place the Options. And added an "add option" Button. Using the Ng-repeat directive on the <li> tab to loop the output,<li> the label will be copied multiple copies according to the options array length in the $scopt. Within the loop range, you can use $index to get the index of the current loop, which you can think of as a public variable to use Directly. At the same time, each <input> element of the loop output also uses Ng-model to bind to the contents of the option in both Directions. Also output a delete link, Click on the time to call $scope in the Deloption method.
When this is done, the list in the template is synchronized with the options array in the data model, and we click on the Add option on the page, an element is added to the array, and each element in the array is fed back into the template in real Time. So in the JS code, we just have to manipulate the options array just enough, no need to append or removed nodes on the page at All.
You can click on the Add option below and delete the test ~
2. Control of individual nodesIn the example above, did you find out that I used the command called Ng-click when I was dealing with the Button's click, why not just use the onclick? is because NG is encapsulated according to its own needs. We have defined the AddOption function within the controller range, and we cannot access it with our regular onclick. In other words, the scope on our page, ng has helped us all to plan, we just need to follow the way it provides to use is Enough.
With the onclick we can think of the HTML node has a lot of other properties, such as class, style, href, checked, disabled, and so on, ng all of these are encapsulated, what is more, In addition to this, Ng also provides many more detailed instructions for controlling the Nodes. These instructions I will study in detail in the future, here, we first take one of the applications to our example, to see the effect First.
I'm going to be a teacher now, Whoa ~
When I create a new question, not limited to a single-choice topic, I want to be able to switch between Single-choice and multi-topic, and in the preview area below, the selection box is also a single box and a Multi-box Switch. On the Code:
HTML section:
<div ng-controller= "testc" > JS code, I just added a type:1 in the questionmodel, the type of the title, 1 for the single, and 2 for multiple Selection. and give the default value of 1.
var Questionmodel = { newtitle: ' new question ', previewtitle: ' preview question ', name: ', fraction: ', type: ' 1 ', options: []};
In html, I added a drop-down box and set up a two-way binding with question.type. What you need to focus on is the preview area Below. I added a CheckBox control to provide a selection box for multiple-choice questions. obviously, the radio and checkbox cannot exist at the same time, so I use the ng-show command to control their presence, Ng-show receive a Boolean value and an expression that evaluates to a Boolean type. Note that the value of ng-show and all other instructions is not a simple string (though it seems to be), but rather a string expression, which has the ability to compute, and I now understand that it will be put in an eval () or similar function execution somewhere in the frame in the Future. The contents of {{}} are the Same.
So here I assign a value of Question.type==1,checkbox ng-show to Radio's ng-show to question.type==2. When the question is a single choice, Radio's ng-show can get the value true, thus showing. Look at the effect below:
Other node control directives can also be used like this, and the idea is to give them certain expressions based on your business Logic. Other controls include event bindings, form controls, and so on, and the limitations of space are not covered Here.
3. Filters (filter)The so-called filter refers to the content of the output format, such as the format of the United States dollar, date and so On. The framework provides itself with some filters, such as sorting, string content Filtering. We can also customize the Filter.
The filter is used in {{}}, and the expression is separated by | Take a date filter example, in the following way:
$scope. nowtime = new Date (). valueOf (); {{nowtime | date: ' Yyyy-mm-dd HH:MM:SS '}}
The formatted date is Output. is not very convenient.
Next combat, Wow ~
Next to the example, I want to show the question in the preview area before the topic, such as [single topic]. In our questionmodel, the value of type is 1 and 2, so all we have to do is pass the filter and show 1 and 2 as single and Multi-choice. go~
Define a filter named TypeFilter in Js:
App.filter (' typeFilter ', function () { var f = function (input) { return input = = ' 1 '?) ' Single choice ': ' Multiple choice '; } Return f;});
How the filter function is used and the execution details are not discussed in this article, so now just understand that you can define a filter. structure is assumed to be a fixed notation, the code is not ugly to understand.
After this filter is defined, we can use it in the Template:
<b>[{{question.type | typefilter}}]{{question.name}}</b> ({{question.fraction}} minutes)
Display the question in front of the topic, and use typefilter, the effect is as Follows:
The monotonous "1" has turned into a "single choice". This is just a simple filter. You can use your imagination to write more powerful Filters.
Vi. directives (directive)I have already mentioned many orders, and now I want to introduce it formally. The instruction is a syntax extension that NG adds to HTML to enhance the expressiveness of the Html. Like the ng-controller, ng-model, etc. that we used before are all Directives. You can also customize the Instructions. NG has a powerful DOM parsing engine inside, so these new tags or tag properties can work just as well as using native html.
It sounds like a cow, so let's try to define a Directive. look, I'm going to be deformed.
I am a teacher, I should only enter a number when I enter a score on a new question, it is illegal to enter other content, and I hope this score is a number between 1~10. Can you complete this verification by adding an attribute to the input box only? Just like using the HTML5 new Required.
We define a directive called Fractionnum as Follows:
App.directive (' fractionnum ', function () { return { link:function (scope, elements, attrs, controller) { Elements[0].onkeyup = function () { if (isNaN (this.value) | | this.value<1 | | this.value>10) { This.style.borderColor = ' Red '; } else{ This.style.borderColor = ";}};}; });
wow, code A lot of levels ah, don't panic, steady! In fact, the end is to return the object with the link field, the value of link is a function that defines the behavior of the Instruction. The current element can be obtained from the parameters passed in, and we can take the current element to the Axe. Here I listen to the KeyUp event of the current element, get the value of the element, and if it is not a number between 1~10, turn the border color of the input box to Red. This command is ready to Work.
As for the incoming four parameters in the end what is the mystery, I have not studied, is not the focus of this article, this is just to do an overview, first put ng out of the meaning of the Slip. Now let's just say that the fixed wording of an instruction is probably the Structure.
The defined instructions can be used in the template, using the following methods:
Score: <input type= "text" ng-model= "question.fraction" fraction-num/><br/>
Add it to the score input box, here to be particularly careful of a writing, I define the name is fractionnum, used in the template need to write fraction-num, because the name contains capital letters, it feels like using CSS property Name. If there is no capital letter at the time of definition, you don't have to worry about it.
Look at the effect, now you can go down and ravage that score input box to go up ~
Vii. Dependency InjectionThrough dependency injection, Ng wants to promote a declarative approach to development, that is, when we need to use a module or service, we do not need to be concerned about how the module is implemented inside, just declare it and use it. Multiple claims can be used in many places, greatly improving Reusability.
Our controller, for example, uses a $scope parameter when it is Defined.
App.controller (' testc ', function ($scope) {});
If we need to do something else here, like interacting with the Browser's address bar. We just need to add one more parameter $location in:
App.controller (' testc ', function ($scope, $location) {});
This allows you to interact with the address bar through $location, and we simply declare that the other code needed for the framework has been injected. We obviously feel that this function is not a regular JavaScript function, in the normal function, the formal parameter for a name can still be run, but here if the $scope for another name, the program can not Run. Because this is a service name that is already defined.
This is the dependency injection MECHANISM. It is logical to infer that we can define our own modules and services, and then declare them where we need them, and inject them into the Framework.
yes, What about my little case? I'm going to need a little bit of demand to experiment with the dependency Injection. I think the question is all the text is too monotonous, I hope the topic can contain Pictures/audio and video, or the option can contain Pictures/audio and video. and, I want to be more flexible, I want to provide several sets of templates to choose the test, choose different templates can create a different style of the problem, such as a template for a plain text questions, template two for the topic with Pictures/audio and video questions, template three for the option with Pictures/audio and video questions, and so On. Note that the template described here and Ng template is not a concept, is my own test template, do not confuse. These templates should be separated from the test questions, and later can be used for other types of questions, such as a blank question ah Jane answer ah. So the question template this thing needs to be made into service.
I don't know if I've made myself clear, but it's a bit around. Take a look at how we define a service:
App.factory (' tpls ', function () { return [' tpl1 ', ' tpl2 ', ' tpl3 ', ' Tpl4 '];});
It looks pretty simple, because I'm just returning an array directly here. In Real-world applications, This should be a request to the server to get to these Templates. Services are defined in several ways, including using the provider method, using the factory method, and using the service Method. The difference between them does not concern for the Moment. We'll just have to create a service right now. I used the factory method. One thing to keep in mind is that the service name provided by the framework starts with $, so it's best not to start with $ for our own definition, to prevent naming conflicts from Occurring.
After defining the good one service, we can declare it in the controller as Follows:
App.controller (' testc ', function ($scope, tpls) { $scope. question = questionmodel; $scope. nowtime = new Date (). valueOf (); $scope. templates = tpls; Assigns a value to the $scope $scope. addoption = function () { var o = {content: '}; $scope. Question.options.push (o); }; $scope. deloption = function (index) { $scope. question.options.splice (index,1);}; });
At this point, if you write the following code in the template, we can obtain the data provided by the service Tpls:
Template: <a href= "javascript:void (0);" ng-repeat= "t in templates" >{{t}} </a><br/>
As the knowledge points a little bit more, my small example is getting more and more plump, to see the full version of It:
To view the full code, please go to RUNJS:HTTP://RUNJS.CN/CODE/95WLWSFH
eight, SummarizeYou can breathe a sigh of relief. The article has finally come to an end here, I do not know whether the above statement can be understood by everyone. Ng contains a lot of content, each of the above concepts can be disassembled a few articles to Explain. So I am here can only be every one donuts, not to pull the details. The idea of this article is "first understand the concept, The example can run up on the line." In the future article will follow my study in-depth Discussion.
Reproduced
About Angularjs (a) Understanding and actual practice of the basic concept of angular