Learning {{AngularJS}} with Examples–Part 1


Client side programming is becoming the one of the main parts of web applications. Now a days, We are seeing the explosion of JavaScript libraries. And the reason is that some JavaScript libraries got very popular and developers took them hand to hand because of its cool feature and almost negligible performance cost, Now in our projects,  count of JavaScript files (plugins and custom files) are increasing rapidly which is making it  unmanageable and unmaintainable. AngularJS provides best of the both the worlds and now a days, it is one of the most talked and used JavaScript framework in web applications. So I have thought to start a series of post on AngularJS. I’ll start from basics and gradually discuss all the features, keeping in mind the.NET Developers.  So let us start learning it. The first questions arises that

What is AngulalJS?

AngularJS is not just another JavaScript library but it provides a framework to write a proper architectured, maintainable and testable client side code. Some of the key points are

  • It follows MVC framework. If you don’t have Idea MVC framework, I’ll suggest you to get an Idea of MVC framework and then start learning AngularJS. You can refer below wiki page on MVC framework.
  • AngularJS is primarily aimed to develop SPAs (Single Page Applications), it means your single HTML document turns into application. But it is also used a lot in ASP.NET and other applications .
  • Allows you to write Unit and integration tests for JavaScript code. Testability is one of the main points, which was kept in mind while writing this framework so it has great support of it.
  • It provides it’s own and very rich list of attribute and properties for HTML controls which increases the usability of it exponentially.It is also called directives.
  • Supports two-way binding that means your data model and control’s data will be in sync.
  • Angular supports Dependency injection. Read more about dependency injection on wiki.
  • Angular library is also available on CDN so you just need to the url of the CDN and it available for use.

It is an Open Source

AngularJS is a open source library and developed and supported by Google. Being an open source, you can go through the code itself and customize it if required. There is lot of support from JavaScript community and even you can contribute to it.  Currently, more that 100 contributors have contributed and it is increasing day by day.

So let’s discuss the main components of AngularJS. These are

Controller – It is main component of AngularJS and contains the state and logic both. It acts as bridge between services and views.

Views/Directives –  Here we generate the UI. Directives extends the HTML element and enables us to generate the complex html easily. Controllers talks to view to both directions.

Services – It contains the core logic and state of the application. In it, we can communicate to server to get and post the data.

Now let’s see all the above components glued with each other.

image

Now you have got the basic explanation about the basics of AngularJS. So let’s jump to the coding. We need to learn two things mentioned below before writing the first application

1- {{expression}} – It is called expressions and JavaScript like code can be written inside. It should be used for mainly small operations in HTML page.

2- $scope – This is one of very important variable used in AngularJS. It provides and link between the data and views. It holds all the required data for the views and used with in the HTML template.

3- ng- – All the elements that are provided by angular starts from ng-. So if you see some attribute that ng- and angular library is also included in the page, then you can assume that this should be angular element only.

4- ng-app – This directive is used to bootstrap the application. Normally, it is put at in top level element like html or body tag. (That will be discussed in details in coming post).

Now lets write our first Hello World application with AngularJS. In this example, I’ll be using the basic construct of AngularJS. I have created Empty Project in Visual Studio and added an HTML page Home.html and written it as

NewExample

This is very simple page using AngularJS. I have encircled and numbered the specific part of the page that are relevant with AngularJS. Let’s discuss it one by one.

1- As discussed earlier that this attribute is required to bootstrap the AngularJS application so I have put it in body element. Here I have put it in body element so it AngularJS can be used inside the body tag. In the above application, I could have put it at h1 element as well because I am using AngularJS inside this tag only. The scope can be displayed pictorially as

image

2- Here I have included the angular library on the page using Google cdn.

3 – When ever we want to use the AngularJS , we need a controller. A JavaScript method HelloWorldCtrl is controller here. I appended Ctrl in the name as a naming convention

4- We already discussed what is $scope. This is a parameter in controller method and we can create dynamic properties and assign values to it, which can be later can be accessed in UI element. We can also create the controller in a new JS file that we’ll see in the coming posts.

image

5- Here we created a new property helloWorldMessage to $scope variable and assigns the message.

6- Now it’s time to use the controller. The controller can be defined over an element as ng-controller=<controller> given in the image as well.

7- Now we see the expression here. As we provided the controller in this element and we can access the property that we defined in the controller that we have used here.

Now it’s to run the application.

runningapp

We can see the message with date and time that we have provided.  Our page got rendered as per expectation. Now Let’s discuss the flow of the angular page. It can be depicted pictorially as

 

AngularFlow-New

 

So the above picture clearly illustrates that How does the flow of Angular page work at high level.

So In this post  we created a very simple page which has all the code on the same HTML page. In the next post, we’ll learn more concept and write a more detailed page and provide a better structure to the application.

Sample is attached with the application.

Hope you have enjoyed the post and will connect you again in next post.

Cheers,
Brij

JavaScript Day : Presented on Arrays in JavaScript

Hi All,

We had organized again a very successful event at C# Corner Delhi Chapter meet fifth times in a row. This was named as JavaScript Day and attended by more that 120 attendees . The entire day we discussed on Core JavaScript and we’ll cover more topics in coming monthly meet.

I discussed on JavaScript array and covered the following topics.

Continue reading

Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

How to consume wcf service using JavaScript Proxy

Hello All,

Today I am going to discuss one another great feature of WCF. Do you know that a WCF service allows us to create a JavaScript Proxy?

Yes it does!!

But let’s first understand that what is a proxy? As we already know whenever we have to use any web service or WCF service, we need to create proxy of that service and with the help of proxy, we use the functionalists provided by the web/WCF service.  Proxy acts a intermediary between the client of the service and the actual service. Proxy provides a simple interface to the consumer of service and all the intricacies like creating a connection, creating and sending the request, getting the response etc is handled by the proxy itself.

Continue reading

Presented on ASP.NET MVC and AJAX at C# Corner Delhi Chapter event

Hi All,

Again we had a very successful event at C# Corner Delhi Chapter July meet on 20the July. This time again despite bad weather, it was attended by more that 100 attendees and we discussed a list of hot technologies. This time Mahesh Chand sir, the founder of C# Corner was also present and discussed about Enterprise architecture.

Continue reading

document.ready vs Javascript onload

It is a small post, who are new to jQuery or just started working with jQuery. As we all know that jQuery is Client side library and provides a wrapper over JavaScript . One of the very good things about jQuery that it runs seamlessly in all leading browsers while you must have faced many issues related to the browsers when you work with JavaScript.

So let’s jump to the topic. What is the difference between let’s first go by an example.

I have created a simple default.aspx page in my asp.net empty application and added few images and put the path from web and added few text. Now I put a general alert and called it on load method of window as

<script type="text/javascript" language="javascript">
        window.onload = OnLoad();
        function OnLoad() {
            alert('I am called by window.onload');
        }
    </script>

Now again I tried to change the code to jQuery document.ready function. And used the code as

$(document).ready(function () {
              OnLoad();
         });
        function OnLoad() {
            alert('I am called by document.ready');
        }

and when I ran it. I got the alert very fast. So what I wanted to point out here that jQuery’s document.ready runs much earlier the JavaScript onload. Why?

document.ready get’s fired as soon as DOM is ready and registered with the browser. It does not wait for the all the resources to get loaded. It allows us some very cool showing, hiding and other effects as soon as user sees the first element on the page.

While Javascript’s onload method gets fired only when all content of the webpage and image, iframes etc get loaded in browser then onload get’s fired.

So do we have a method in JavaScript that works in similar way as document.ready?

Partially yes.

We have a method called DOMContentLoaded  that is actually called by jQuery from document.ready. But that’s not it.  DOMContentLoaded is not available to every browser and versions. For IE > 9,  onreadystatechange works in the same way. In case nothing works in browser, jQuery has a fallback and it implemented own logic to traverse the DOM and check the when the DOM got registered and fires document.ready accordingly.

So I hope you all got to know the basic difference between these two.

Cheers,
Brij