[javascript] "Pensando en AngularJS" si tengo un fondo jQuery?


Imperativo → declarativo

En jQuery, los selectores se usan para encontrar elementos DOM y luego enlazar / registrar manejadores de eventos para ellos. Cuando se desencadena un evento, ese código (imperativo) se ejecuta para actualizar / cambiar el DOM.

En AngularJS, desea pensar en vistas en lugar de elementos DOM. Las vistas son HTML (declarativo) que contienen directivas AngularJS. Las directivas configuran los controladores de eventos detrás de escena para nosotros y nos dan enlaces de datos dinámicos. Los selectores rara vez se utilizan, por lo que la necesidad de ID (y algunos tipos de clases) se ve muy disminuida. Las vistas están ligadas a los modelos (a través de ámbitos). Las vistas son una proyección del modelo. Los eventos cambian los modelos (es decir, los datos, las propiedades del alcance) y las vistas que proyectan esos modelos se actualizan "automáticamente".

En AngularJS, piense en los modelos, en lugar de los elementos DOM seleccionados por jQuery que contienen sus datos. Piense en vistas como proyecciones de esos modelos, en lugar de registrar devoluciones de llamadas para manipular lo que ve el usuario.

Separación de intereses

jQuery emplea JavaScript discreto : el comportamiento (JavaScript) está separado de la estructura (HTML).

AngularJS usa controladores y directivas (cada uno de los cuales puede tener su propio controlador y / o funciones de compilación y vinculación) para eliminar el comportamiento de la vista / estructura (HTML). Angular también tiene servicios y filtros para ayudar a separar / organizar su aplicación.

Ver también https://stackoverflow.com/a/14346528/215945

Diseño de la aplicación

Un enfoque para diseñar una aplicación AngularJS:

  1. Piensa en tus modelos. Cree servicios o sus propios objetos JavaScript para esos modelos.
  2. Piensa cómo quieres presentar tus modelos: tus puntos de vista. Cree plantillas HTML para cada vista, usando las directivas necesarias para obtener un enlace de datos dinámico.
  3. Adjunte un controlador a cada vista (usando ng-view y routing, o ng-controller). Haga que el controlador encuentre / obtenga solo los datos del modelo que la vista necesita para hacer su trabajo. Haga que los controladores sean lo más delgados posible.

Herencia Prototypal

Puede hacer mucho con jQuery sin saber cómo funciona la herencia prototípica de JavaScript. Al desarrollar aplicaciones AngularJS, evitará algunos errores comunes si comprende bien la herencia de JavaScript. Lectura recomendada: ¿Cuáles son los matices del alcance de la herencia prototípica / prototípica en AngularJS?


Supongamos que estoy familiarizado con el desarrollo de aplicaciones del lado del cliente en jQuery , pero ahora me gustaría comenzar a usar AngularJS . ¿Puedes describir el cambio de paradigma que es necesario? Aquí hay algunas preguntas que pueden ayudarlo a enmarcar una respuesta:

  • ¿Cómo puedo diseñar y diseñar aplicaciones web del lado del cliente de manera diferente? ¿Cuál es la mayor diferencia?
  • ¿Qué debería dejar de hacer / usar? ¿Qué debería empezar a hacer / usar en su lugar?
  • ¿Hay consideraciones / restricciones del lado del servidor?

No estoy buscando una comparación detallada entre jQuery y AngularJS .

I find this question interesting, because my first serious exposure to JavaScript programming was Node.js and AngularJS. I never learned jQuery, and I guess that's a good thing, because I don't have to unlearn anything. In fact, I actively avoid jQuery solutions to my problems, and instead, solely look for an "AngularJS way" to solve them. So, I guess my answer to this question would essentially boil down to, "think like someone who never learned jQuery" and avoid any temptation to incorporate jQuery directly (obviously AngularJS uses it to some extent behind the scenes).


jQuery makes ridiculously long JavaScript commands like getElementByHerpDerp shorter and cross-browser.


AngularJS allows you to make your own HTML tags/attributes that do things which work well with dynamic web applications (since HTML was designed for static pages).


Saying "I have a jQuery background how do I think in AngularJS?" is like saying "I have an HTML background how do I think in JavaScript?" The fact that you're asking the question shows you most likely don't understand the fundamental purposes of these two resources. This is why I chose to answer the question by simply pointing out the fundamental difference rather than going through the list saying "AngularJS makes use of directives whereas jQuery uses CSS selectors to make a jQuery object which does this and that etc....". This question does not require a lengthy answer.

jQuery is a way to make programming JavaScript in the browser easier. Shorter, cross-browser commands, etc.

AngularJS extends HTML, so you don't have to put <div> all over the place just to make an application. It makes HTML actually work for applications rather than what it was designed for, which is static, educational web pages. It accomplishes this in a roundabout way using JavaScript, but fundamentally it is an extension of HTML, not JavaScript.

They're apples and oranges. You don't want to compare them. They're two different things. AngularJs has already jQuery lite built in which allows you to perform basic DOM manipulation without even including the full blown jQuery version.

jQuery is all about DOM manipulation. It solves all the cross browser pain otherwise you will have to deal with but it's not a framework that allows you to divide your app into components like AngularJS.

A nice thing about AngularJs is that it allows you to separate/isolate the DOM manipulation in the directives. There are built-in directives ready for you to use such as ng-click. You can create your own custom directives that will contain all your view logic or DOM manipulation so you don't end up mingle DOM manipulation code in the controllers or services that should take care of the business logic.

Angular breaks down your app into - Controllers - Services - Views - etc.

and there is one more thing, that's the directive. It's an attribute you can attach to any DOM element and you can go nuts with jQuery within it without worrying about your jQuery ever conflicts with AngularJs components or messes up with its architecture.

I heard from a meetup I attended, one of the founders of Angular said they worked really hard to separate out the DOM manipulation so do not try to include them back in.

jQuery is a DOM manipulation library.

AngularJS is an MV* framework.

In fact, AngularJS is one of the few JavaScript MV* frameworks (many JavaScript MVC tools still fall under the category library).

Being a framework, it hosts your code and takes ownership of decisions about what to call and when!

AngularJS itself includes a jQuery-lite edition within it. So for some basic DOM selection/manipulation, you really don't have to include the jQuery library (it saves many bytes to run on the network.)

AngularJS has the concept of "Directives" for DOM manipulation and designing reusable UI components, so you should use it whenever you feel the need of doing DOM manipulation related stuff (directives are only place where you should write jQuery code while using AngularJS).

AngularJS involves some learning curve (more than jQuery :-).

-->For any developer coming from jQuery background, my first advice would be to "learn JavaScript as a first class language before jumping onto a rich framework like AngularJS!" I learned the above fact the hard way.

Buena suerte.

Can you describe the paradigm shift that is necessary?

Imperative vs Declarative

With jQuery you tell the DOM what needs to happen, step by step. With AngularJS you describe what results you want but not how to do it. More on this here . Also, check out Mark Rajcok's answer.

How do I architect and design client-side web apps differently?

AngularJS is an entire client-side framework that uses the MVC pattern (check out their graphical representation ). It greatly focuses on separation of concerns.

What is the biggest difference? What should I stop doing/using; what should I start doing/using instead?

jQuery is a library

AngularJS is a beautiful client-side framework, highly testable, that combines tons of cool stuff such as MVC, dependency injection , data binding and much more.

It focuses on separation of concerns and testing ( unit testing and end-to-end testing), which facilitates test-driven development.

The best way to start is going through their awesome tutorial . You can go through the steps in a couple of hours; however, in case you want to master the concepts behind the scenes, they include a myriad of reference for further reading.

Are there any server-side considerations/restrictions?

You may use it on existing applications where you are already using pure jQuery. However, if you want to fully take advantage of the AngularJS features you may consider coding the server side using a RESTful approach.

Doing so will allow you to leverage their resource factory , which creates an abstraction of your server side RESTful API and makes server-side calls (get, save, delete, etc.) incredibly easy.

As a JavaScript MV* beginner and purely focusing on the application architecture (not the server/client-side matters), I would certainly recommend the following resource (which I am surprised wasn't mentioned yet): JavaScript Design Patterns , by Addy Osmani, as an introduction to different JavaScript Design Patterns . The terms used in this answer are taken from the linked document above. I'm not going to repeat what was worded really well in the accepted answer. Instead, this answer links back to the theoretical backgrounds which power AngularJS (and other libraries).

Like me, you will quickly realize that AngularJS (or Ember.js , Durandal, & other MV* frameworks for that matter) is one complex framework assembling many of the different JavaScript design patterns.

I found it easier also, to test (1) native JavaScript code and (2) smaller libraries for each one of these patterns separately before diving into one global framework. This allowed me to better understand which crucial issues a framework adresses (because you are personally faced with the problem).

Por ejemplo:

  • JavaScript Object-oriented Programming (this is a Google search link). It is not a library, but certainly a prerequisite to any application programming. It taught me the native implementations of the prototype, constructor, singleton & decorator patterns
  • jQuery / Underscore for the facade pattern (like WYSIWYG's for manipulating the DOM)
  • Prototype.js for the prototype/ constructor/ mixin pattern
  • RequireJS / Curl.js for the module pattern/ AMD
  • KnockoutJS for the observable, publish/subscribe pattern

NB: This list is not complete, nor 'the best libraries'; they just happen to be the libraries I used. These libraries also include more patterns, the ones mentioned are just their main focuses or original intents. If you feel something is missing from this list, please do mention it in the comments, and I will be glad to add it.