About Angularjs (a) understanding and actual practice of the basic concept of angular

Source: Internet
Author: User
Tags border color

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 data

First, 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 template

When 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 output

Continue 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 nodes

In 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 Injection

Through 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}}&nbsp;&nbsp;</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, summarize

You 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.