Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am a jQuery programmer, and have just started using angularjs. I have read a few tutorial on how to do use angular, but I am not clear on why to use it. Hence, I need following help from the community:

  1. Please validate my understanding of Angularjs - Angular makes you think MVC, which perhaps means that you view your webpage as a template + data combination. 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 appears characteristically similar to jsp way of designing webpages.

  2. For simple DOM manipulation, which does not 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 don't affect the model.

ps: if the question appears unconstructive or at the wrong place, please suggest me where shall I move it to. The jQuery/angular dilemma is certainly there in the developer community

share|improve this question

closed as primarily opinion-based by Andy Hayden, Andrew, lserni, DNA, alko Dec 18 '13 at 0:09

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

11  
I'd recommend checking out this great post: stackoverflow.com/questions/14994391/… –  Anthony Aug 24 '13 at 1:32
    
The question remains ... if I am making a simple webpage which has a form, a few buttons (which hide/unhide on hovering/clicking over certain elements, etc), is Angular required? I am not making single view webapp ... just a webpage. –  Amarsh Aug 24 '13 at 1:42
2  
Yes, Angular works perfectly for your use case and will result in significantly less code to get things working, even though it's just a webpage. And who knows, it's just a webpage right now but might evolve in the future. With Angular, you can simply augment the page's controller with new components, or even re-use existing components. I've used jQuery for a long time and just started learning Angular a few months ago, and honestly I have no desire to keep writing jQuery spaghetti :) If you insist on jQuery for your non-data page manipulations, you can perform that easily with directives. –  Anthony Aug 24 '13 at 1:46
    
But of course no need to go overboard if it's literally a one form page and will always be that. –  Anthony Aug 24 '13 at 1:53
3  
This would be better off over on programmers.stackexchange.com. SO is more of a Q&A format for actual coding issues. –  Ben Lesh Dec 3 '13 at 21:56

1 Answer 1

up vote 195 down vote accepted

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]'));

Quite a bit of code after all..

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 in practice, the dom manipulation is declared in the dom.

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?

Update: Not Convinced?

It appears that people commonly misunderstand some of the points made above and I believe that this is the result of a misunderstanding about the question and also that my answer was primarily aimed toward the OP's concerns and not the overall topic. I'll briefly lay out some issues to point in the right direction (read more about each topic elsewhere).

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.

Misko Hevery is a better developer than you.

Probably.. Yes, I'm claiming that you should at least consider using Angular (if appropriate for your application) because Google made it. Google also did all of this: http://en.wikipedia.org/wiki/List_of_Google_products

When it comes to technology, "Google says so" is enough for me. They've earned that.

share|improve this answer
14  
+1 for explanation with demo... –  CJ Ramki Feb 6 at 7:51
3  
I am still searching for the reason; being in Javascript for ages I agreed that it is a smart development. However it is only , purely giving us MVC. Today also I don't do binding of each html object with my JSON data. It is my small plugin in jquery that does that thing. The directives looks cool however one can have server side controls and use as is.... overall I am still finding one reason except that it gives you MVC, which is COOL! –  codebased Feb 11 at 4:35
2  
In your example, I'm not what is so much better than the Angular approach. If you'd written your jQuery example with all of the function calls inline, you end up with code that is basically the same length and complexity as the AngularJS example. –  Brian May 22 at 17:47
1  
@Brian That's not quite the point I was most trying to stress. I'll update this with more details when I get the chance. The emphasis should be on the point I started with - "augment" your html via angular, then just use html to do "view" things. In other words, the view is the official record. This is an elegant, modular, and simple way to structure code. Also, I wouldn't write everything inline as that would harm readability. I think both examples are equally optimized for readability and thus are a good comparison. –  m59 May 22 at 20:10
1  
I dont think the demo demonstrates a reason to use Angular. It seems way too complicated for what its trying to do. The only real benefit I see is the two way data binding, but you could just as easily create a jquery plugin to do that. –  qodeninja Jun 13 at 18:20

protected by Derek 朕會功夫 Sep 16 at 3:55

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.