top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration
Print Preview

Key differences between AngularJS and jQuery?

0 votes
65 views

In this Article I am trying to cover the major differences between JQuery and Angular.js, comment and share this if you like.

Framework
If you compare jQuery and Angular, the former is a library and the latter is a framework. You can plug the library in your project and either use it fully, partially or not use it all. It’s like a plugin, a supplement to your JS project. With a framework – you have to play by its rules, either use it fully or don’t use it all. Angular.js is a MVC framework, it has model, view and controller which is one of the most popular software development architectures today. When developing with Angular, you have to start from the ground up with your architecture in mind. Although it’s possible to add Angular to your existing project, it’s just add more complexity in the long run.

Don’t use Angular the jQuery way
There are thousands of jQuery plugins out there, it’s very to just plug something in and forget about it. Angular has different structure, it’s recommended to use directives instead. Try to develop “the angular way” instead of just patching the code with old good plugins. It’s not even necessary to add jQuery to your project, Angular comes with jqLite (simplified version of jQuery for basic DOM manipulation).

Single page application
The architecture of the Angular app is different, most of them are single page applications (SPA). Instead of loading all the code at once like we do with jQuery and showing and hiding different parts of the DOM, we load templates on demand (using http requests). That way the application stays more modular and easier to maintain, debug or update. I like the approach where you create controller, module, HTML template and CSS file for every view in your app.

Data Binding
Data binding is one of the best features in Angular.js (one way or two way binding). This makes data completely independent from the presentation, unlike in jQuery where your model (data) is the DOM. For example, data comes from HTTP request (http module), it’s added to the scope ($scope.data) in controller and rendered in HTML template as {{ data }}.
This way you as a developer know where data is coming from and where you need to go to make any changes. In jQuery if you have something like $(‘#data’).render(); it may render a whole new page and you won’t event know what it is or where this content came from.

Summary
Angular doesn’t replace jQuery, it doesn’t compete with jQuery, they both can be used in the same application. jQuery for DOM manipulation, Angular – for structure. In fact there is nothing better to do DOM manipulation than jQuery.

References

It is not my own creation, all information was collected from internet and compiled.
posted Oct 3 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button


Related Articles

AngularJS applications may need to communicate across the controllers. Such a communication might be needed to send notifications or to pass data between the controllers. Although there can be different approaches to achieve this goal, one that is readily available is the event system of $scope and $rootScope. Both of these objects - $scope and $rootScope - support three methods namely $broadcast(), $emit() and $on() that facilitate event driven publisher-subscriber model for sending notifications and passing data between the controllers. In this article I will discuss how to raise events using $broadcast() and $emit() and then how to handle those events using $on().

If you ever used jQuery custom events, the AngularJS event system mentioned above should look familiar to you. However, unlike jQuery custom events the AngularJS event system requires bit more understanding as multiple controllers are involved.

Overview of $broadcast(), $emit() and $on()

Before you dig into the examples discussed below it would be worthwhile to take a quick look at the purpose and use of $broadcast(), $emit() and $on().

$broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite. It sends an event upwards from the current controller to all of its parent controllers. From the syntax point of view a typical call to $broadcast() and $emit() will look like this:

$scope.$broadcast("MyEvent",data);
$scope.$emit("MyEvent",data); 

Here, MyEvent is the developer defined name of the event that you wish to raise. The optional data parameter can be any type of data that you wish to pass when MyEvent is dispatched by the system. For example, if you wish to pas data from one controller to another that data can go as this second parameter.

An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. A typical call to $on() will look like this:

$scope.$on("MyEvent", function(evt,data){ 
  // handler code here });

Now that you know what $broadcast(), $emit() and $on() do let's put them to use in the following examples.

Event system on $scope and $rootScope

When it comes to communicating between two or more AngularJS controllers there can be two possible arrangements:

  • Controllers under consideration are nested controllers. That means they have parent-child relationship.
  • Controllers under consideration are sibling controllers. That means they are at the same level without any parent-child relationship.

In the former case you will use $broadcast(), $emit() and $on() on the $scope object whereas in the later case you will use these methods on the $rootScope object. Let's see each of the possibility with an example.

Nested controllers

To see how $broadcast(), $emit() and $on() can be used with nested controllers, you will develop a simple application as shown below:

image

The above application consists of three AngularJS controllers - MyController1, MyController2 and MyController3 - nested inside each other. The outermost <div> (MYController1) has a button for raising an event handled SendDown. Similarly, the innermost <div> (MyController3) has a button for raising an event named SendUp. Thus the SendDown event is raised in MyController1 and can be handled by MyController1, MyController2 and MyController3. On the same lines SendUp event us raised inside MyController3 and is handled by MyController3, MyController2 and MyController1. Notice that although both the events look similar, the SendDown event travels from MyController1 to MyController3 whereas SendUp travels from MyController3 to MyController1.

Both the events send a string data ("some data") when the corresponding event is dispatched. You can easily substitute an object instead of string data. Upon handling the respective events a message is shown inside each <div> just to confirm that the handler has indeed executed and the data is received successfully.

Ok. Now let's see the code of all the controllers mentioned above. The MyController1 looks like this:

app.controller("MyController1", function ($scope, $rootScope) {

    //broadcast the event down
    $scope.OnClick = function (evt) {
        $scope.$broadcast("SendDown", "some data");
    }

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler 
                          of MyController1 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler 
                          of MyController1 : " + data;
    });
});

MyController1 does three things. Firstly, it raises SendDown event using $broadcast() method. It uses $broadcast() because we wish to send the event from parent controller to child controllers. So, the SendData is dispatched by MyController inside the click event handler of the Broadcast button. Secondly, MyController1 handles SendData event using $on(). Since SendData is raised by MyController itself this step might not be needed at all. I am still handling the event just to point out that something like that is possible. The SendDown handler simply sets Message property of the $scope object. This Message will be displayed in the corresponding <div> element. Thirdly, MyController1 handles SendUp event. Recollect that this event is raised by MyController3 in the upward direction (child to parent) and MyController1 simply handles it.

The code of MyController2 is quite straightforward and is shown below:

app.controller("MyController2", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController2 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController2 : " + data;
    });

});

MyController2 simply handles SendDown and SendUp events and sets Message property on the $scope object.

Finally, MyController3 does the following:

app.controller("MyController3", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController3 : " + data;
    });

    //emit SendUp event up
    $scope.OnClick = function (evt) {
        $scope.$emit("SendUp", "some data");
    }

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController3 : " + data;
    });
});

MyController3 is quite similar to MyController1. However, it raises SendUp event using $emit() method. This way SendUp event travels from child (MyController3) to the parents (MyController2 and MyController1). The event handlers of SendDown and SendUp simply assign the Message property.

The HTML markup of the page will look like this:

<body ng-app="MyApp">
 <div ng-controller="MyController1">
  <input type="button" value="Broadcast Down" 
         ng-click="OnClick($event)" />
  <h4>{{Message}}</h4>
   <div ng-controller="MyController2">
    <h4>{{Message}}</h4>
    <div ng-controller="MyController3">
     <h4>{{Message}}</h4>
     <input type="button" value="Emit Up" 
            ng-click="OnClick($event)" />
    </div>
   </div>
  </div>
</body>

If you run the application and click on the Broadcast button you should get results as shown above. Clicking on Emit button will produce the following result:

image

Sibling controllers

The above examples achieves communication and passes data between controllers having parent-child relationship. What if you wish to achieve the communication between sibling controllers? If so, you need to use $rootScope instead of $scope. That's because since there is no parent-child relationship, each controller will have its own scope and there won't be any inherited scope as in the previous example. Moreover, $emit() won't serve much purpose in case of sibling controllers. This is because $rootScope is a container scope for all the other scopes and can dispatch events only to its child controllers. So, only $broadcast() will serve some useful purpose in this case.

Assuming that there are three sibling controllers - MyController1, MyController2 and MyController3 - the application will take this form:

image

As before there are three controllers but they are siblings. The topmost <div> (MyController1) has Broadcast button that raises SendDown event on $rootScope object. All the controllers handle the SendData event and set Message property on their individual $scope object. The complete code of all the three controllers is shown below:

app.controller("MyController1", function ($scope, $rootScope) {
    //raise event on $rootScope
    $scope.OnClick = function (evt) {
        $rootScope.$broadcast("SendDown", "some data");
    }

    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController1 : " + data;
    });

});

app.controller("MyController2", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController2 : " + data;
    });

});

app.controller("MyController3", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController3 : " + data;
    });
});

As you can see, this time $broadcast() is called on $rootScope object to raise SendDown event. SendDown is handled by individual $scope objects as before.

A word of caution before I conclude this article - although event system discussed above looks straightforward and simple, if used excessively it can get messy in terms of overall management and application flow. So, give a thought before you jump in to raise too many events.

That's it for this article! Keep coding.

READ MORE
Selector PatternExampleDescription
Element name$('div')Selects all <div> elements
:first$('div:first')Selects first <div> element in a DOM hierarchy.
:last$('div:last')Selects last <div> element in a DOM hierarchy.
Multiple elements$('p, div, code')Selects <p>,<div> and <code> elements
parent descendant$('div p')Selects all <p> elements which is descendant of <div>
parent child$('div > p')Selects <p> element which is child of <div>
*$(*)Selects all elements
#Id$("#myDiv")Selects element whose id is myDiv
element#id$("div#myDiv")Selects <div> element whose Id is myDiv
#id, #id$("#myDiv1, #myDiv2")Selects multiple elements whose id is myDiv1 or myDiv2.
.class$(".myCSSClass")Selects all the elements with class=myCSSClass.
.class .class$(".myCSSClass1, .myCSSClass2 ")Finds all elements whose class attribute is set to myCSSClass1 or myCSSClass2
element.class$("div.myCSSClass")Finds all <div> elements with class=myCSSClass
:first-child$("p:first-child")Selects all <p> elements which is the first child of its parent element. (parent element can be anything)
:last-child$("p:last-child")Selects all <p> elements which is the last child of its parent element. (parent element can be anything)
:nth-child(n)$("p:nth-child(5)")Selects all <p> elements which is the 5th child of its parent element. (parent element can be anything)
:nth-last-child(n)$("p:nth-last-child(2)")Selects all <p> elements which is the 2nd last child of its parent element. (parent element can be anything)
:only-child$("p:only-child")Selects all <p> elements which is the only child of its parent element. (parent element can be anything)
[attribute]$('[class]')Selects all the elements with the class attribute(whatever the value).
[element[attribute]$("div[class]")Selects all the <div> elements that have a classattribute(whatever the value).
element[attribute = value]$("div[class='myCls']")Selects all the <div> elements whose class attributes are equal to myCls.
element[attribute |= value]$("div[class|= 'myCls']")Selects all the <div> elements whose class attributes are either equal to myCls or starting with myCls string followed by a hyphen (-).
element[attribute *= "value"]$("div[class *= 'myCls']")Selects <div> elements whose class attributes contains myCls.
element[attribute ~= "value"]$("div[class ~= 'myCls']")Selects div elements whose class attributes contains myCls, delimited by spaces.
element[attribute $= "value"]$("div[class $= 'myCls']")Selects <div> elements whose class attribute value ends with myCls. The comparison is case sensitive.
element[attribute != "value"]$("div[class != 'myCls']")Selects <div> elements which do not have class attribute or value does not equal to myCls.
element[attribute ^= "value"]$("div[class ^= 'myCls']")Selects <div> elements whose class attribute value starts with myCls.
:contains("value")$("div:contains('tutorialsteacher')"Selects all <div> elements that contains the text 'tutorialsteacher'
:input$(":input")Selects all input elements.
:button$(":button")Selects all input elements where type="button".
:radio$(":radio")Selects all input types where type="radio"
:text$(":radio")Selects all input elements where type="text" .
":checkbox"$(":checkbox")Selects all checkbox elements.
:submit$(":submit")Selects all input elements where type="submit".
:password$(":password")Selects all input elements where type="password".
:reset$(":reset")Selects all input elements where type="reset".
:image$(':image')Selects all input elements where type="image".
:file$(':file')Selects all input elements where type="file".
:enabled$(':enabled')Selects all enabled input elements.
:disabled$(':disabled')Selects all disabled input elements.
:selected$(':selected')Selects all selected input elements.
:checked$(':checked')Selects all checked input elements.
:hidden$(':hidden')Selects all hidden elements.
:visible$(':visible')Selects all visible elements.
:odd$('tr:odd')Selects all odd rows. (1,3,5,7..)
:even$('tr:even')Selects all even rows.(0,2,4,6..)

 

READ MORE

In this article I am trying to to cover important features of AngularJS, which are as follows - 

a. Scope: Scope is a JavaScript object that refers to the application model. It acts as a context for evaluating angular expressions. Basically, it acts as glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your AngularJS app. AngularJS has two scope objects: $rootScope and $scope.

b. Controller: AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

c. Model: Models are plain old JavaScript objects that represent data used by your app. Models are also used to represent your app's current state.

d. View: The view is responsible for presenting your models data to end user. Typically it is the HTML markup which exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

e. Services: Services are singletons, which are objects that are instantiated only once per app (by the $injector). They provide an interface to keep together methods that relate to a specific function. AngularJS provides many inbuilt services for example, $http, $route, $window, $location etc. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

f. Data-binding: AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e. the sections of code which is included in many places with little or no alteration). Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way databinding to handle the synchronization of data between model and view.

g. Directives: Directives might just be the killer feature of AngularJS. Directives allow us to extend the grammar of the web through reusable HTML elements, attributes, and classes. AngularJS directives are extended HTML attributes with the prefix ng-.

h. Filters: Filters are used to change modify the data and can be clubbed in expression or directives using pipe character. AngularJS filters can be used to transform data:
1.currency -Format a number to a currency format.
2. filter - Select a subset of items from an array.
3. lowercase - Format a string to lower case.
4. orderBy - Orders an array by an expression.
5. uppercase - Format a string to upper case.

READ MORE
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...