AngularJS 比 jQuery 有什么优势? [英] What does AngularJS do better than jQuery?

查看:22
本文介绍了AngularJS 比 jQuery 有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用 jQuery 库,刚刚开始使用 AngularJS.我已经阅读了一些关于如何使用 Angular 的教程,但我不清楚为什么或何时使用它,或者与仅使用 jQuery 相比我可能会发现什么好处.

在我看来,Angular 让你想到了 MVC,这可能意味着你将网页视为模板 + 数据的组合.每当您觉得需要动态数据时,您都可以使用 {{data bindings}}.然后 Angular 将为您提供一个 $scope 处理程序,您可以静态地或通过调用 Web 服务器来填充它.这在特征上类似于 JSP 设计网页的方式.我需要为此使用 Angular 吗?

对于简单的 DOM 操作,涉及数据操作(例如:鼠标悬停时的颜色变化,点击时隐藏/显示元素),jQuery 或 vanilla JS 就足够了,更干净.这假设 angular 的 mvc 中的 model任何反映页面上数据的东西,因此,CSS 属性如颜色、显示/隐藏、等更改不会影响模型.在 DOM 操作方面,Angular 是否比 jQuery 或 vanilla JS 有任何优势?

与 jQuery 和插件一起做的事情相比,Angular 可以做什么使其对开发有用?

解决方案

数据绑定

<块引用>

你四处制作你的网页,并继续把{{data绑定}} 每当你觉得你会有动态数据.角意志然后为您提供一个 $scope 处理程序,您可以填充它(静态或通过调用网络服务器).

这是对数据绑定的一个很好的理解.我想你已经明白了.

DOM 操作

<块引用>

对于简单的DOM操作,不涉及数据操作(例如:鼠标悬停时的颜色变化,点击时隐藏/显示元素),jQuery 或老式 js 就足够了,而且更干净.这假设angular 的 mvc 中的模型是任何反映页面数据的东西,因此,颜色、显示/隐藏等 css 属性不会发生变化影响模型.

我可以在这里看到您关于简单"DOM 操作更简洁的观点,但这种情况很少见,而且必须非常简单".我认为 DOM 操作是其中一个领域,就像数据绑定一样,Angular 真正发挥了作用.理解这一点还将帮助您了解 Angular 如何考虑其视图.

我将首先比较 Angular 方式和原生 js 的 DOM 操作方式.传统上,我们认为 HTML 不做"任何事情,而是这样编写.所以,内联js,比如onclick"等是不好的做法,因为它们把做"放在HTML的上下文中,而不是做".Angular 颠覆了这个概念.在编写视图时,您认为 HTML 能够做"很多事情.这种能力在 angular 指令中被抽象出来,但是如果它们已经存在或者你已经编写了它们,你不必考虑如何"完成它,你只需使用在这个增强"的 HTML 中提供给你的能力角度允许您使用.这也意味着您的所有视图逻辑都真正包含在视图中,而不是包含在您的 javascript 文件中.同样,推理是在您的 javascript 文件中编写的指令可以被认为是增加了 HTML 的能力,因此您让 DOM 担心操纵自己(可以这么说).我会用一个简单的例子来演示.

这是我们要使用的标记.我给它起了一个直观的名字.

<div rotate-on-click="45"></div>

首先,我想评论一下,如果我们已经通过自定义 Angular 指令为 HTML 提供了此功能,那么我们已经完成了.那是一股清新的空气.稍后会详细介绍.

使用 jQuery 实现

现场演示(点击).

function rotate(deg, elem) {$(elem).css({webkitTransform:'旋转('+度+'度)',mozTransform: '旋转('+度+'度)',msTransform:'旋转('+度+'度)',o变换:'旋转('+度+'度)',变换:'旋转('+度+'度)'});}函数 addRotateOnClick($elems) {$elems.each(function(i, elem) {变量度 = 0;$(elem).click(function() {deg+= parseInt($(this).attr('rotate-on-click'), 10);旋转(度,这个);});});}addRotateOnClick($('[点击时旋转]'));

使用 Angular 实现

现场演示(点击).

app.directive('rotateOnClick', function() {返回 {限制:'A',链接:函数(范围,元素,属性){var 度 = 0;element.bind('点击', function() {deg+= parseInt(attrs.rotateOnClick, 10);元素.css({webkitTransform:'旋转('+度+'度)',mozTransform: '旋转('+度+'度)',msTransform:'旋转('+度+'度)',o变换:'旋转('+度+'度)',变换:'旋转('+度+'度)'});});}};});

非常轻巧,非常干净,这只是一个简单的操作! 在我看来,角度方法在所有方面都胜出,尤其是如何抽象出功能以及如何在 DOM 中声明 dom 操作.该功能通过 html 属性挂接到元素上,因此无需通过选择器查询 DOM,并且我们有两个很好的闭包 - 一个用于指令工厂的闭包,其中变量在指令的所有用法中共享,以及 link 函数(或 compile 函数)中指令的每次使用一个闭包.

双向数据绑定和 DOM 操作指令只是让 Angular 变得很棒的开始.Angular 提倡所有代码都是模块化的、可重用的、易于测试的,并且还包括一个单页应用程序路由系统.需要注意的是,jQuery 是一个,其中包含常用的便利/跨浏览器方法,而 Angular 是一个用于创建单页应用程序的全功能框架.angular 脚本实际上包含了它自己的精简版"jQuery 版本,因此可以使用一些最重要的方法.因此,您可能会争辩说使用 Angular 是使用 jQuery(轻松地),但 Angular 提供了更多魔法"来帮助您创建应用程序.

这是一篇提供更多相关信息的好帖子:如果我有 jQuery 背景,我如何在 AngularJS 中思考"?

一般差异.

以上几点针对 OP 的具体问题.我还将概述其他重要差异.我建议您也对每个主题进行额外阅读.

Angular 和 jQuery 无法合理地进行比较.

Angular 是一个框架,jQuery 是一个库.框架有自己的位置,库也有自己的位置.然而,毫无疑问,一个好的框架在编写应用程序方面比库更强大.这正是框架的意义所在.欢迎你用普通的 JS 编写你的代码,或者你可以添加一个常用函数库,或者你可以添加一个框架来大大减少完成大多数事情所需的代码.因此,更合适的问题是:

为什么要使用框架?

好的框架可以帮助您构建代码,使其模块化(因此可重用)、DRY、可读、高性能和安全.jQuery 不是一个框架,因此它在这些方面没有帮助.我们都见过典型的 jQuery 意大利面条式代码墙.这不是 jQuery 的错——这是不知道如何构建代码的开发人员的错.但是,如果开发人员确实知道如何构建代码,他们最终会编写某种最小的框架"来提供我刚才讨论的基础(架构等),或者他们会添加一些东西.例如,你可能会添加 RequireJS 以作为编写优秀代码的框架的一部分.

以下是现代框架提供的一些功能:

  • 模板
  • 数据绑定
  • 路由(单页应用)
  • 干净、模块化、可重复使用的架构
  • 安全
  • 为方便起见的附加功能/特性

在我进一步讨论 Angular 之前,我想指出 Angular 并不是唯一的一种.例如,Durandal 是一个构建在 jQuery、Knockout 和 RequireJS 之上的框架.同样,jQuery 本身无法提供 Knockout、RequireJS 以及构建在它们之上的整个框架所能提供的功能.只是没有可比性.

如果你需要摧毁一个星球并且你有一颗死星,请使用死星.

Angular(重新审视).

基于我之前关于框架提供什么的观点,我想赞扬 Angular 提供它们的方式,并试图澄清为什么这实际上优于 jQuery.

DOM 参考.

在我上面的例子中,jQuery 必须挂钩到 DOM 以提供功能是绝对不可避免的.这意味着视图 (html) 关注功能(因为它标有某种标识符 - 例如图像滑块"),而 JavaScript 关注提供该功能.Angular 通过抽象消除了这个概念.使用 Angular 正确编写代码意味着视图能够声明自己的行为.如果我想显示一个时钟:

完成.

是的,我们需要使用 JavaScript 使之变得有意义,但我们正在以与 jQuery 方法相反的方式执行此操作.我们的 Angular 指令(在它自己的小世界中)已经增强"了 html,而 html 将功能挂钩到自身中.

MVW 架构/模块/依赖注入

Angular 为您提供了一种直接的方式来组织您的代码.视图事物属于视图(html),增强的视图功能属于指令,其他逻辑(如 ajax 调用)和功能属于服务,服务和逻辑与视图的连接属于控制器.还有一些其他的 Angular 组件可以帮助处理服务的配置和修改等.您创建的任何功能都可以通过 Injector 子系统在您需要的任何地方自动使用,该子系统负责整个应用程序的依赖注入.在编写应用程序(模块)时,我将其分解为其他可重用模块,每个模块都有自己的可重用组件,然后将它们包含在更大的项目中.一旦你用 Angular 解决了一个问题,你就会以一种有用的、结构化的方式自动解决它,以便将来重用,并且很容易包含在下一个项目中.所有这一切的巨大好处是您的代码将更容易测试.

在 Angular 中让事情工作"并不容易.

谢天谢地.前面提到的 jQuery 意大利面代码来自一个开发人员,该开发人员做了一些工作"然后继续前进.你可以写出糟糕的 Angular 代码,但要做到这一点要困难得多,因为 Angular 会为此与你争吵.这意味着您必须(至少在某种程度上)利用它提供的干净架构.换句话说,用 Angular 写坏代码更难,但写干净代码更方便.

Angular 远非完美.Web 开发世界一直在发展和变化,并且有新的更好的方法被提出来解决问题.例如,Facebook 的 React 和 Flux 与 Angular 相比有一些很大的优势,但也有自己的缺点.没有什么是完美的,但 Angular 一直并且现在仍然很棒.正如 jQuery 曾经帮助网络世界向前发展一样,Angular 也是如此,未来还会有很多.

I have mainly been using the jQuery library and have just started using AngularJS. I have read a few tutorials on how to use Angular, but I am not clear on why or when to use it, or what benefits I may find in comparison to just using jQuery.

It seems to me that Angular makes you think MVC, which perhaps means that you view your webpage as a template + data combination. You use {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate statically or through calls to the web server. This appears characteristically similar to JSP way of designing webpages. Do I need Angular for this?

For simple DOM manipulation, which does not involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or vanilla JS is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, CSS properties like color, display/hide, etc changes don't affect the model. Does Angular have any advantages over jQuery or vanilla JS for DOM manipulations?

What can Angular do that makes it useful for development in comparison to what jQuery can do along with plugins?

解决方案

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I "think in AngularJS" if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

这篇关于AngularJS 比 jQuery 有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆