The things about Angularjs and the jquery framework

Source: Internet
Author: User

This article mainly introduces the differences between jquery and Angularjs, this article focuses on a familiar with the jquery programmer how to deal with the angularjs of some of the changes in programming ideas, the need for friends can refer to the next

The most recent study of Angularjs's experience is that it is completely different from the previous jquery and the design ideas of jquery's various libraries. If you do not realize this, and for the previous jquery development programmer, to directly learn angularjs, it is likely to learn a long time do not know what this thing is exactly what, what to do, and how to combine the UI, and so on, I also looked around for information to see, Here to learn some of their experiences and share with you, in order to make progress together.

The original question: If I am familiar with using jquery to develop client applications, then how do I get started angularjs, can describe the required pattern changes, the following questions can help you to give an answer:

1. What is the difference between designing a client Web application and what is the biggest difference?

2. Should I stop using those technologies and what technologies are used instead?

3. Are there things or restrictions that need to be considered on the service side?

Reply:

1. Do not first design your page, and then through the DOM operation to modify it

In jquery, you first design a page and then dynamically modify its content, because jquery is designed to scale up and add and modify content in this context, but in angular you have to design your architecture in your mind, and from the very beginning, you will have to abandon the " I have a DOM element and I'm going to let it do something ", substituting" what I need to accomplish, then design your app, and finally design your view layer. "

2. Do not use Angularjs to extend jquery

Accordingly, don't exist say let jquery do something, then add Angularjs function on this basis to manage the idea of model and controller. So I generally don't recommend ANGULARJS developers to use jquery at the same time, at least not to recommend it until they have adapted to Angularjs's development model, but when you really start adapting to Angularjs, you'll find it a tempting thing to do.

I've seen some developers wrap up a jquery plugin with 150 to 200 lines of code using the ANGULARJS callback and the $apply method, which makes the code look complicated, but in fact they let the plugins run! The problem is that in most cases the jquery plug-in can be rewritten with angularjs and possibly with less code, and this rewrite makes the code more intuitive and readable, which is obviously too much of a jquery code encapsulation.

So finally said, when you encounter problems, first of all to think Angularjs thinking, if not find a solution, you can turn to others, if no one can give a satisfactory answer, we then test female jquery, do not let jquery become your crutch, Otherwise you will never be able to master Angularjs.

3. Consider the architecture as the center

First you need to know that single-page apps are web apps, and they're not traditional multi-page sites. So we want to think about it as both a server and a client-side developer, and we need to think about how we can divide our applications into separate, extensible, and testable parts.

So then how do we use angularjs thinking to work, here are some basic guidelines for comparing it to jquery:

The following is the view layer for an app:

In jquery, we dynamically modify this view, and we use UL to define a dropdown menu

The code is as follows:

<ul class= "Main-menu" >

<li class= "Active" >

<a href= "#/home" >Home</a>

</li>

<li>

<a href= "#/menu1" >menu 1</a>

<ul>

<li><a href= "#/sm1" >submenu 1</a></li>

<li><a href= "#/sm2" >submenu 2</a></li>

<li><a href= "#/sm3" >submenu 3</a></li>

</ul>

</li>

<li>

<a href= "#/home" >menu 2</a>

</li>

</ul>

In jquery, we used the following logic to use this Dropdownmenu

The code is as follows:

$ ('. Main-menu '). Dropdownmenu ();

Let's look back at this view and you'll see that it's not very straightforward, and for small applications it's possible, but it's confusing and difficult to maintain for large applications;

In Angularjs, this view is actually a view-based feature that we can define for UL

<ul class= "Main-menu" dropdown-menu>
...
</ul>

Both of these methods actually do the same thing, but in the ANGULARJS mode anyone who sees this view template knows what to do next. Whenever a new member joins the development team he can see here and find a command called Dropdownmenu to manipulate the view, he doesn't need to guess the right answer or review other code, and the view tells us exactly what it's going to do, compared to jquery, It's more concise.

Often some angularjs novice ask the question: How can I find all the link of a certain type and add a directive on this basis, but when we answer "you shouldn't do this, you're a half-jquery half-angularjs idea" when They would have been surprised.

The problem is that they're trying to do something with jquery in a angularjs context, which is usually not a good way, and you don't need to do any DOM operations outside of the instructions, and the instructions are added directly to the view, so the intent is already obvious. Remember, do not design and then modify, but first have the structure and then in this framework to design.

Data binding

This is by far the most compelling feature of Angularjs, where it discards the manipulation of the DOM in terms of data binding, all of which are automatically updated by Angularjs, and you don't have to write code to manipulate the DOM, in jquery, We often respond to events and modify views in the following ways:

$.ajax ({

URL: '/myendpoint.json ',

Success:function (data, status) {

$ (' Ul#log '). Append (' <li>data received!</li> ');

}

});

In relation to such a view

<ul class= "Messages" id= "Log" >
</ul>

In addition to the mixed problems, we still have questions about how to express my intentions as I mentioned earlier. But more importantly, we have to manually reference and update this DOM node, if we want to delete one, then we have to programmatically manipulate that DOM element, then how do we test the logic outside the DOM node, or do we want to change the way we display it?

The above code looks messy and fragile, but in angularjs we can do this:

$http ('/myendpoint.json '). Then (function (response) {
$scope. Log.push ({msg: ' Data received! '});
});

Our view should look like this

<ul class= "Messages" >
<li ng-repeat= "entry in log" >{{entry.msg}}</li>
</ul>

In that case, our view can do the same.

<div class= "Messages" >
<div class= "alert" ng-repeat= "entry in log" >
{{entry.msg}}
</div>
</div>

Now we do not use the UL, but instead of using the bootstrap pop-up box, but we do not have to modify the controller in the code, more importantly, no matter how the data is modified, the view layer will automatically change, very concise!

Although I will not do a demo here, but you need to know that data binding is bidirectional, you can edit the data by adding the instructions <input ng-model= "entry.msg"/>, and there are many other exciting places.

Differentiate the model layer

In jquery, the DOM resembles a model, but in Angularjs we have a different model layer in jquery so that we can manage it in whatever way we want it to be, completely independent of the view. This approach helps us to be data-bound and to maintain a focus on separation, and can be better testable.

Separation of attention points

All of this is related to the overall topic: let you focus on separation, your view layer displays records, your model layer represents data, and you have a service layer to perform these reusable tasks. You use directive to perform DOM operations and extend your view and connect it to the controller, which is why I've mentioned in other ways about enhancing testability.

Dependency Injection

To help us solve the separation of concerns is dependency injection (DI), if you are a server developer (Java or PHP), you may already be familiar with the concept, but if you are engaged in client development, you will feel that the concept may be somewhat redundant and purely in the pursuit of fashion, but it is not.

In a broad sense, di means that you are free to declare components and then instantiate them from those components, for granted. You don't have to know the loading order, the file location, and so on, this magic is not immediately visible, but I'll give an example: Test.

We say that in an application, we need a service that relies on application state and local storage to perform server-side storage through a rest API, and when we test our controller, we don't have to communicate with the server, after all, just testing the controller. We only add a mock service that is the same as our original component, and the injector ensures that our controller gets a virtual service, and that the controller itself does not have to understand the difference.

So tell me about the test.

4. Test-driven development

This part is the third part of the architecture, but he is so important that I need to put it in the most important position.

How many of the jquery plugins we've seen, used and written, have a set of test components? In fact, this is because jquery is not easy to control on the test, but Angularjs is different.

In jquery, the only way to test is to use a demo page to create a standalone component that allows our tests to perform DOM operations. We will then have to develop a separate component and then integrate it into our application, which is more inconvenient Ah! In many cases, when we use jquery development to actually do a lot of repetitive development rather than test-driven development, does this blame us?

But in Angularjs we can focus on the separation point, so we can do some test-driven development. For example, we have a directive to illustrate our current path in the menu, which we can declare in the view:

<a href= "/hello" when-active>hello</a>

Well, now we can write a test to test this non-existent instruction When-active.

It (' should add ' active ' when the route changes ', inject (function () {
var elm = $compile (' <a href= "/hello" When-active>hello</a> ') ($scope);

$location. Path ('/not-matching ');
Expect (Elm.hasclass (' active ')). Tobefalsey ();

$location. Path ('/hello ');
Expect (Elm.hasclass (' active ')). Tobetruthy ();
}));

We run the test case directly, you will find that it is a failure, this time you need to create this command, as follows:

. directive (' whenactive ', function ($location) {
return {
Scope:true,
Link:function (scope, element, Attrs) {
Scope. $on (' $routeChangeSuccess ', function () {
if ($location. path () = = element.attr (' href ')) {
Element.addclass (' active ');
}
else {
Element.removeclass (' active ');
}
});
}
};
});

Run this test case again, you will find that through and the menu is displayed as requested, our development is both repeatable and testability, very cool!

5. Conceptually, directives are not packaged jquery

You often hear that DOM operations can only be done in the instruction, which is necessary and you have to take it seriously.

Let's go into the discussion,

Some instructions simply decorate our view (for example, Ngclass), so it is sometimes possible to manipulate the DOM directly, but when an instruction is similar to a small object and has its own template, it should be considered a separate concern, that is, Its template needs to be separated from the execution logic in link and other controller functions.

Angularjs has a complete set of tools that can be simpler for this separation, using ngclass instructions, we can dynamically update class, use Ngbind we can do bidirectional data binding, use Ngshow and nghide we

You can display and hide an element programmatically, as well as many of the instructions we write ourselves. In other words, we can do all the work without DOM operations, the fewer DOM operations, the easier the instructions to test, the easier it is to specify their style attributes, the easier it will be to change them in the future, and the easier it will be to reuse and distribute.

I've seen a lot of angularjs newbies use the instructions to encapsulate a bunch of jquery code, in other words, since I can't do DOM operations in the controller, I can put him in the instructions, although this is a lot better than manipulating the DOM directly, but it's still wrong.

Take a look at our record above, even if we put it in an instruction, we still need to operate it in a angular way, this way does not do DOM operation! Dom operations are needed in many cases, but this is much less than you think. It's a better way to ask ourselves if we need to do this in the DOM.

Here is a simple example of a pattern that I often see that we need I a switchable button:

The code is as follows:
. directive (' mydirective ', function () {
return {
Template: ' <a class= ' btn ' >toggle me!</a> ',
Link:function (scope, element, Attrs) {
var on = false;

$ (Element). Click (function () {
on =!on;
$ (Element). Toggleclass (' active ', on);
});
}
};
});

In the above example, the following error is present:

1. First of all, jquery is unnecessary and the work here does not need to be jquery!

2. Second, even though we have introduced jquery on the page, there is no reason to use it, we can use angular.element and our components can run, even if jquery is not introduced in this project.

3. Thirdly, assuming that jquery is needed in our directives, we can use Jqlite to replace it, so long as we introduce jquery, we do not have to use angular.element;

4. Four, and the 3rd is very close, the jqlite element does not have to use $ wrap, element elements passed into the link function is already a jquery object;

5. Five, as we have said before, why not mix up our templates and logic?

The above instructions can be rewritten in the following way, even in the most complex cases.

The code is as follows:
. directive (' mydirective ', function () {
return {
Scope:true,
Template: ' <a class= ' btn "ng-class=" {active:on} "ng-click=" Toggle () ">toggle me!</a>",
Link:function (scope, element, Attrs) {
Scope.on = false;

Scope.toggle = function () {
Scope.on =!scope.on;
};
}
};
});

Template element is in the Templates property, you can easily replace its style, and the logic does not have to change, to achieve full reuse!

There are other benefits, such as simple testing, no matter what the template is, the API will not change, so refactoring it is simple. You can change your template as many times as you want without changing the instructions, and your test will always pass, no matter how you change it!

So the instruction is not a collection of jquery code, such as a function, but the extension of the HTML code, if the HTML code does not implement the functionality you need, you can write a command to implement it, and then use it as HTML.

In another way, ANGULARJS, if you don't do something extra, think about how we can use the Ngclick,ngclass directive.

Summarize

Don't always use jquery, don't even reference it, it will stop you from moving forward when we get back to the question-you know how you solve the problem in Angularjs in jquery, but when you use selectors such as $, you have to think that they actually imprison Angularjs, If you don't know how to do it without jquery, then ask someone, one at a time, the best way is not to use jquery, and using jquery will only lead to a boost in your workload.

The things about Angularjs and the jquery framework

Related Article

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.