AngularJs and jquery comparative analysis, super detailed!
Nothing to do, found on the internet a comparison of Angularjs and jquery article. Just recently, I'm also studying Angularjs. The friends you need can be consulted.
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. What technologies should I discontinue using, and which technologies should I use as an alternative?
3. Is there something that needs to be considered in the service side or is there some restrictions?
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 angularjs you have to design your architecture in your mind first,
From the beginning, you have to discard "I have a DOM element and want it to do something", substituting "what do I need to accomplish, then design your application, and finally design your view layer".
2. Do not use Angularjs to extend jquery
Accordingly, do not exist say let jquery do something, then add Angularjs function on this basis to let it manage model and controller idea. 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 a lot of 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 extremely complex, but in fact they let the plugins run! The problem is that, in most cases, jquery plugins can be rewritten with angularjs, and may only use a very small amount of code, and this rewrite makes the code intuitive and easy to understand, which is obviously too good to encapsulate the jquery code directly.
So in the end, when you meet the problem, you must first think with angularjs thinking, if you can't find a solution, you can turn to the community, if no one can give a simple plan, then consider using 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 of all you need to know that single page applications belong to Web applications, they are not traditional multi-web sites, so we want to think as a server and client developer, and we have 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
Copy the code code 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
Copy the code code 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
Copy the code code as follows:
<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:
Copy the code code as follows:
$.ajax ({
URL: '/myendpoint.json ',
Success:function (data, status) {
$ (' Ul#log '). Append (' <li>data received!</li> ');
}
});
In relation to such a view
Copy the code code as follows:
<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:
Copy the code code as follows:
$http ('/myendpoint.json '). Then (function (response) {
$scope. Log.push ({msg: ' Data received! '});
});
Our view should look like this
Copy the code code as follows:
<ul class= "Messages" >
<li ng-repeat= "entry in log" >{{entry.msg}}</li>
</ul>
In that case, our view can do the same.
Copy the code code as follows:
<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:
Copy the code code as follows:
<a href= "/hello" when-active>hello</a>
Well, now we can write a test to test this non-existent instruction When-active.
Copy the code code as follows:
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:
Copy the code code 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:
Copy the code code 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.
Copy the code code 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.
It can be said that the advantages of ANGULARJS and jquery and even design ideas have different, according to my understanding. The former is the first to build a good house, and so on. And the latter is, the people who need to settle in, with the bricks themselves to repair a building. As to which one is more convenient and suitable for you, it varies from person to person.
AngularJs and jquery comparative analysis, super detailed!