Home > Web Front-end > JS Tutorial > A brief analysis of the difference between jQuery and AngularJS_AngularJS

A brief analysis of the difference between jQuery and AngularJS_AngularJS

WBOY
Release: 2016-05-16 16:17:20
Original
1467 people have browsed it

I have been studying angularjs recently. The biggest feeling is that it is completely different from the previous jQuery and various library design concepts based on jQuery. If you cannot realize this and programmers who have done jQuery development before, go and learn angularjs directly. If so, it is possible that after studying it for a long time, you still don’t know what this thing can be used for, how to use it, how to combine it with the UI, etc. I found an article about this on stackoverflow, and it was quite rewarding after reading it. On this basis Translate it into Chinese so that everyone can learn from it together.

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

1. What are the differences when designing client web applications? What is the biggest difference?

2. Which technologies should I stop using and which technologies should I use as replacements?

3. Are there anything or restrictions that need to be considered on the server side?

Answer:

1. Don’t design your page first and then modify it through DOM manipulation

In jQuery, you first design a page, and then dynamically modify its content. This is because jQuery is designed to expand and significantly increase and modify content under this premise, but in angularjs , you must design your structure in your mind first,

From the beginning, you have to abandon "I have a DOM element and I want it to do something" and replace it with "What task do I need to accomplish, and then design your application, and finally design you View view layer".

2. Do not use angularjs to extend jQuery

Accordingly, don’t have the idea of ​​letting jQuery do certain things, and then adding the functions of angularjs to let it manage the model and controller. Therefore, I generally do not recommend AngularJS development novices to use jQuery at the same time, at least not until they have adapted to the AngularJS development model. But when you really start to adapt to the AngularJS way, you will find that this is very tempting. People things.

I have seen many developers encapsulate jQuery plug-ins with 150 to 200 lines of code using angularjs callbacks and $apply methods. This method makes the code look extremely complicated, but in fact they let these plug-ins run Get up! The problem is that in most cases jQuery plug-ins can be rewritten in angularjs and may only use a very small amount of code. At the same time, this rewriting makes the code intuitive and easy to understand, which is obviously better than doing the jQuery code directly. Encapsulation.

So in the end, when you encounter a problem, you must first think in terms of angularjs. If you can't find a solution, you can ask the community for help. If no one can give a simple solution, then consider it. Use jQuery, don't let jQuery become your crutch, otherwise you will never master AngularJS.

3. Think architecture-centric

First of all, you need to know that single-page applications are web applications. They are not traditional multi-page websites, so we have to think as a server and client developer at the same time. We need to think about how to divide our applications into Independent, extensible and testable parts.

So how do we use AngularJS thinking to work next? Here are some basic guidelines after comparing it with jQuery:

The following is the view layer of an application:

In jQuery, we dynamically modify this view. We use ul to define a dropdown menu

Copy code The code is as follows:





In jQuery, we use this dropdownMenu using the following logic




Copy code

The code is as follows:




Copy code

The code is as follows:

The two methods actually do the same thing, but in the AngularJS method anyone who sees this view template will know what to do next. Whenever a new member joins the development team, he can look here and find that there is an instruction called dropdownMenu to operate the view. He does not need to guess the correct answer or review other code, the view tells us directly. What it does, it's simpler than jQuery.

Some AngularJS newbies often ask this question: How can I find all links of a certain type and add a directive based on it, but when we answer "You shouldn't do it this way, you are Half jQuery half angularjs idea", they will be surprised.

The problem is that they are trying to do something with jQuery in the context of AngularJS, which is generally not a good way to do it. You don't need to do any DOM manipulation outside of the directive, which is added directly to the view. , so the intention is already obvious. Remember, don’t design it first and then modify it, but have a structure first and then design it within this framework.
Data Binding

This is by far the most eye-catching feature of AngularJS. In terms of data binding, it abandons the way of operating the DOM, and all this is done by AngularJS to automatically update the view. You don’t have to write code to operate the dom. , in jQuery, we often respond to events and modify views in the following ways:

Copy code

The code is as follows:



Relative to such a view




Copy code

The code is as follows:

In addition to the problem of confusion, we also have the problem I mentioned earlier of how to indicate one's intentions. But more importantly, we must manually reference and update this DOM node. If we want to delete one of them, we must programmatically operate that DOM element. So in this case, how do we test the DOM node? What about external logic, or do we want to change the display method?

The above code seems messy and fragile, but in AngularJS, we can do this:

Copy code The code is as follows:

$http( '/myEndpoint.json' ).then( function ( response ) {
$scope.log.push( { msg: 'Data Received!' } );
});

Our view should look like this

Copy code The code is as follows:


  • {{ entry.msg }}



In that case, our view could also look like this

Copy code The code is as follows:



{{ entry.msg }}


Now we don’t use ul, but use Bootstrap’s pop-up box, but we don’t need to modify the code in the controller. More importantly, no matter how the data is modified, the view layer will automatically change accordingly, which is very simple. !

Although I won't do a demonstration here, you need to know that data binding is two-way, you can edit the data by adding the directive , and there are many others exciting place.

Difference model layer

In jQuery, DOM is similar to a model, but in AngularJS, we have a different model layer than jQuery so that we can manage it in any way we want. It is completely independent of the view. of. This approach helps us perform data binding and maintain separation of concerns, and allows for better testability.

Separation of concerns

The above is all related to this 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 directives to perform DOM operations and extend your view and connect it to the controller, which is why I mentioned elsewhere about improving testability.

Dependency Injection

What helps us solve the separation of concerns is dependency injection (DI). If you are a server-side developer (Java or PHP), you may already be familiar with this concept, but if you are engaged in client-side development, You would think that this concept might be a bit redundant and purely fashionable, but in fact it is not.

From a broad perspective, DI means that you can freely declare components and then instantiate from those components, which is a given. You don't have to know the load order, file locations, that kind of thing, the magic isn't immediately apparent, but I'll give an example: testing.

We said that in the application, we need a service that relies on application state and local storage to perform server-side storage through a rest API. When we test our controller, we do not have to communicate with the server, after all Just testing the controller. We just add a mock service that is the same as our original component. The injector ensures that our controller gets a dummy service. The controller itself does not need to know the difference.

Let’s talk about testing.

4. Test-driven development

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

Of all the jQuery plugins we have seen, used, and written, how many have a testing component? In fact, there are not many. This is because jQuery is not easy to control during testing, but AngularJS is different from this.

In jQuery, the only way to test is to use a demo page to create an independent component so that our test can perform DOM operations. Next we have to develop a separate component and integrate it into our application. How inconvenient this is! In many cases, when we use jQuery to develop, we actually do a lot of repetitive development rather than test-driven development. Can you blame us?

But in AngularJS we can focus on separation points, so we can do some test-driven development. For example, we have a directive to describe our current path in the menu. We can declare it in the view like this:

Copy code The code is as follows:

Okay, now we can write a test to test this non-existent instruction when-active

Copy code The code is as follows:

it( 'should add "active" when the route changes', inject(function() {
var elm = $compile( 'Hello' )( $scope );

$location.path('/not-matching');
Expect( elm.hasClass('active') ).toBeFalsey();

$location.path( '/hello' );
Expect( elm.hasClass('active') ).toBeTruthy();
}));

We run the test case directly, and you will find that it fails. At this time, you need to create this command, as follows:

Copy code The code is 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 it passed and the menu is displayed as requested. Our development is both iterative and testable, which is very cool!

5. Conceptually, directives are not packaged jQuery

You often hear that DOM operations can only be done in instructions. This is a must and you must take it seriously.

Let’s dive in,

Some directives just decorate our views (such as ngClass), so sometimes it is okay to directly manipulate the dom, but when a directive is similar to a widget and has its own template, then it should be treated as a separate concern Point, this means that its template needs to be separated from the execution logic in the link and other controller functions.

AngularJS has a complete set of tools that can make this separation easier. Using the ngClass directive, we can dynamically update classes, using ngBind we can perform two-way data binding, and using ngShow and ngHide we

You can show and hide an element programmatically, including many instructions we wrote ourselves. In other words, we can complete all the work without DOM operations. The fewer DOM operations, the easier it is to test instructions, the easier it is to specify their style attributes, the easier it is to change them in the future, and the easier they are to reuse and distribute.

I have seen many AngularJS newbies using directives to encapsulate a large sequence of jQuery code. In other words, since I can’t perform dom operations in the controller, I can put it in the directive, although this is much better than directly operating the dom. , but still wrong.

Look at our record above, even if we put it in a directive, we still need to operate it in the Angular way, which does not perform dom operations! There are many times when DOM manipulation is needed, but this situation is much rarer than you think. When we need to do DOM operations, we first ask ourselves whether we must do this here. This is a better way.

The following is a simple example to illustrate a pattern I often see, where we need a toggle button:

Copy code The code is as follows:

.directive( 'myDirective', function () {
Return {
Template: 'Toggle me!',
link: function (scope, element, attrs) {
          var on = false;

$(element).click( function () {
on = !on;
                      $(element).toggleClass('active', on);
            });
}
};
});

In the above example there is the following error:

1. First of all, jQuery is unnecessary, jQuery is not required at all to work here!

2. Second, even if we have introduced jQuery into the page, but we have no reason to use it, we can use angular.element and our components will be able to run, even if jQuery is not introduced in this project.

3. Third, assuming that jquery is needed in our instructions, we can use jqLite to replace it. Just introduce jQuery, so we don’t have to use $ but use angular.element;

4. Fourth, and closely related to the third point, jqLite elements do not need to be wrapped with $. The element element passed to the link function is already a jQuery object;

5. Fifth, as we said before, why not mix our templates and logic?

The above command can be rewritten as follows, making it look so simple even in the most complex cases.

Copy code The code is as follows:

.directive( 'myDirective', function () {
Return {
scope: true,
Template: 'Toggle me!',
link: function (scope, element, attrs) {
scope.on = false;

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

The template element is in the template attribute, you can easily replace its style, and the logic does not need to change at all, achieving complete reuse!

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

So the instruction is not a collection of jQuery codes, such as functions, etc., but an extension of the HTML code. If the HTML code cannot achieve the function you need, you can write an instruction to implement it, and then use it like HTML Use it.

To put it another way, if AngularJS does not do extra things, think about how we can use the ngClick and ngClass instructions?

Summary

Don’t always use jquery, don’t even reference it, it will stop you in your tracks, when we come back to the problem - you know how you solve the problem in AngularJS the jquery way, but when you use selectors like $ etc. , you have to think about how they actually imprison AngularJS. If you don’t know how to implement it without jQuery, then ask others and ask again and again. The best way is not to use jQuery. Using jQuery will only cause your work. Volume increase.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template