Tuesday, April 29, 2014

Learning AngularJS Part 3: Directives, Data Binding and Filters

Here is Previous Part of this series:

Continuing the series of Learning AngularJS a guide for beginners, in this post we will see the Directives Filters and Data Bindings. If you are new to AngularJS I would recommend you to read the series of article from start.





To start developing an application you need to download AngularJS Library or you can use CDN for the benefits of caching. include the downloaded AngularJS to your HTML just before the closing body tag this will make sure that your document is loaded when your AngularJS start running.

<html>
<head></head>
  <body>

     <script src="angular.js"></script>
  </body>
</html>

That is it! you have everything you need to code for AngularJS application. You can use any IDE for coding I would recommend Visual Studio 2013 because of some better JavaScript intellisense.

Now you have included library for AngularJS you are ready to code, to code with AngularJS you need to use Directives.

What are Directives?

Directives are most important or I would say core components of AngularJS. Directives are nothing but HTML tags and attributes. These are the way to use AngularJS extended HTML functionality. Using directives you can teach HTML new features by writing your own custom directives. AngularJS comes with a bunch of built-in directives like ng-app, ng-hide,ng-show, ng-repeat, ng-class and many others.

Directives are markers on the HTML page that tells AngularJS to bind that particular directive functionality(behavior) on a specified element.

Lets see a simple Hello World application:
<html ng-app="">
 <head>
    <title>Anular JS</title>
 </head>
 <body>
     <div id="container" ng-init="name='Zaheer Ahmed'">
     Your Name: <input ng-model="name" type="text" />
 
     Hello AngularJS world!!!!
     My Name is {{name}}.</div>
   </body>
</html>

Here is working demo, Practice here.

So Here we have designed a simple application and we use some AngularJS directives, attributes starting with ng are angular directives.

We started with ng-app the most important directive of AngularJS.

It declares the scope of your application that is the reason it is mostly put at the html tag itself, but it can be use inside html the only thing need to be considered is that AngularJS directive only works within the scope of ng-app directives.

Here we use ng-app attribute without value because for this simple application we do not have any controller or scope (view model). So it works withing this scope. But if we want to use data from this view in our controller then we need to initialize value for this attribute i.e, ng-app='myApp'.

Then we used the ng-init let see it after ng-model, ng-model directive initialized a property in memory with the name given as value, ng-model is one of the ways to bind the $scope(View-Model) properties to the element, since in this example we do not have any controller so the scope of this variable will only be limited  for this View.

Since we have pre-initialize the variable name using ng-init so it is already available in the memory so it will use this value and bind it to input input field. So when you run this application you will see input has value 'Zaheer Ahmed' because name was initialize by it.

So these are some basic directive you mostly need to use, as you start practicing you will get familiar to many built-in directives. Here is complete API reference available, you can search and get information about all directives or you can download Angular Cheat Sheet.

Data Binding

Data binding in AngularJS is really simple, as we did in above code simply wrap the variable as {{variable}} on any element, that element is now bounder to the data. ng-model is also a way to bind using attribute as we did in above code example.

Binding in AngularJS is two ways which means if you bounded an element to a data now if that element lets say input change that property the original data in your controller will also be updated or if you update the value of data from controller element will also show changes.

So AngularJS made this so simple using one attribute otherwise developer need to write the code to detect onchange event for getting change from element and also need to update element to update element value.

How Filters work?

Filters are the way to pass all of  your data collection to a particular condition. like searching, sorting etc. For example in above code we printed the name enter by user in input field we want to make it upper-case or there is an array we want to upper-case all string there we need to use filters. Filters are applied on a data using bar separator.

So changing above code to :

<html ng-app="">    
 <head>
    <title>Anular JS</title>
 </head>    
 <body>
    <div id="container" ng-init="name='Zaheer Ahmed'">
      Your Name: <input ng-model="name" type="text" /> 

      Hello AngularJS world!!!!
      My Name is {{name | uppercase}}.
    </div>
  </body>
</html>

above code will automatically convert input value to upper-case. Here is demo.

Let see another example where we filter data using user input:
<html ng-app> 
 <head>
    <title>Anular JS</title>
 </head>
 <body>
    <div id='container' ng-init="names=['Ahmed','John','Jeff',Zaheer']">
       search : <input type="text" ng-model="searchKeyword" />

       <div style='background:#E4E8EA;padding:10px;'>
          Here is list of user name:
          <ul ng-repeat="name in names | filter:searchKeyword">
              <li>{{name | uppercase}}</li>
          </ul>
       </div>
   </div>
 </body>
</html>

Here is demo, for practice.

Here we initialize an array using ng-init directive and bind input field with another variable searchKeyword like we did in our previous example.

Here we used another directive ng-repeat, this directive keeps repeating element to the number of times data present in given collection. This is really helpful for-example you have 50 users data and you want to show in a particular format. You need to write 50 times the same HTML but with ng-repeat you just need to create a template and  using this directive repeat it number of times you want.

Now here we use the filter after bar separator  name in names | filter:searchKeyword  here we are telling it to filter the collection for searchKeyword, so it will give us only the list containing the keyword input by user.

As you see how simple it was to filter a collection. There are many built-in filters available which include currency[:symbol]filter:expressionjson, lowecase, uppercase, orderby etc.

So it was Directives filters and data binding in AngularJs. Hope now you have some base knowledge and with time and practice you will be familiar with more of these.

Hope you find this helpful. Please do comment if you want to see any particular topic of AngularJS in this series and also give your valuable feedback and don't forget to share with friends.

Here is Next Part of this series:

Sunday, April 27, 2014

Learning AngularJS Part 2: Model View Controller

Here is Previous Part of this series:

So here we are with the second part of the series learning AngularJs guide for beginners. If you have not read the first Article I strongly recommend you to see the first article of the series Introduction to AngularJS

In this article we are going to see Models Views and Controllers and will see model part of the application also called View Model or $scope in details. It is a really important part of AngularJs.









View Controller and Scope

Views

The AngularJS application has a View which is the part rendered in a browser, it is the way to show the data to users. View uses the directives, filters and data-bindings. But to make view simple and easy to maintainable we do not put all of our code into these View. Separating code from views also make it easy to write tests for the business logic.

Controller

We put all of our logic to container called controller in Angular. The Controller controls and prepare the data into the form so it can be rendered at the View. So Controller actually transforms the bunch of data into the representational form and also take from view and set into the Model after validating it. The controller is responsible for communicating the server code to fetches the data from a server using Ajax calls and send the data to back-end server from Views.



Scope / View Model

The most important part of the architecture is $scope or Model or View Model. It is the actual link between Controllers and Views. There can be a controller which we can bind to two or more views. Like controller for a registration form can have a different view for desktop and another view for mobile. In real Controller has no information about the Views and similarly View is independent of logic implemented or data present in the Controller. $scope acts as the communication tunnel between the Views and Controller.

 First Code Example

We will try to implement a simple demo, so it becomes more easier to understand the concept of View Controller and scope. In this simple example we list down the Users. You will definitely find very easy to implement it.

Here is the code of View:
<div ng-controller="MyFirstController">
    <h2>List of User</h2>
    <ul>
        <li ng-repeat="user in Users">
            {{user.firstName}} {{user.lastName}} live in {{user.city}}
        </li>
    </ul>
</div>
Here we are using some AngularJS directives we will see these directives in later articles. Just to make it understand we are telling view that you expect data from this controller using ng-controller directive. It is not necessary to declare a controller here we can set it at run-time with routing.

Now here is the controller:
var myApp = angular.module('myApp',[]);

function MyFirstController($scope) {
    $scope.Users = [
        {firstName: 'Nico',lastName:'braga', city:'Karachi' },
        {firstName: 'Bob',lastName:'Rita', city:'Lahore' },
        {firstName: 'John',lastName:'Smith', city:'New York' },
    ];
}
Here is demo fiddle, you can change and practice over it.

Here we initialize an angular module application myApp and then added a controller to it. This controller contains a list of users. Then we access the controller and show the list of user in HTML View.

So this was the architecture use in Angular, It is really easy to maintain and much cleaner than ordinary dynamic application code. In next article I will try to cover directives filters and data bindings. Please provide your valuable feedback by comments and let me know if any particular topic you want to see in this series. Don't forget to share it with your friends.

Here is Next Part of this series:

Saturday, April 26, 2014

Learning AngularJS Part 1: Introduction to AngularJS

Here is Next Part of this series:

Recently I started learning AngularJs, It was very difficult for me to find some good detailed articles or beginner tutorials on AngularJS. I have to read from many different articles, books and tutorials. So I decided to put step by step help for beginners like me. So they get complete required help from one single channel. Since AngularJS is a very rich framework so I decided to write in a series of post. So beginners easily follow and track their performance.

Lets start with Introduction to AngularJs. There is no coding in this article we will only see what AngularJs is.

What Is AngularJS?

AngularJS is JavaScript MVC structured framework for dynamic web applications. It is created by Google to allow you to develop well architectures and easily maintainable web-applications. AngularJS allows you to extend HTML by adding your own custom tags and attributes. With angularJS you need to write lesser code as It allows you to reuse components. With very easy way of two-way bindings and dependency injection (we will see these in details coming articles) , you need to code less than you have to write before AngularJS. As AngularJs is client-sided so all these things happening in browsers.

HTML is designed for static sites, it is beautiful declarative language. But developing a dynamic site with HTML you need to do many tricks to achieve you want. With AngularJS extending the HTML it is really simple to make a dynamic site in a proper MVC structure. The directive is the terminology use for extending HTML, with these directives one can achieve:

  1. You can create a template and reuse it in application multiple times.
  2. Can bind data to any element in two ways, means changing data will automatically change element and changing element will change the data.
  3. You can directly call the code-behind code in your html.
  4. Easily validate forms and input fields before submitting it.
  5. You can control complete dom structure show/hide, changing everything with AngularJS properties.


AngularJS a complete Solution


AngularJS not only allow you to write your custom HTML. It allows you to completely control your DOM and easily managed your Ajax code which previously you need to manage your own. It has included many other features including:
  • All the features you need to build a CRUD application like data-binding,  data validation, url routing, reusable HTML components and most importantly dependency injection.
  • JavaScript Testing: AngularJS allows you to write basic flow end-to-end testing,  unit-testing, ui mocks.
  • Proper directory architectures of HTML code in MVC structure.

Until now we use term dependency-injection many times, some of you might not be aware of it. Dependency Injection is a software design pattern, allows you to inject any dependent module at run time means you can anytime change some feature or complete module of any dependent module with this pattern. AngularJs also follow the dependency-injection for example you can change the routing module with your custom written library or may switch many available pre-written libraries for routing.

If you were previously coding with jQuery you might use it for many features which AngularJS already included in it, so instead of depending on two different libraries which is possible to achieve with only having AngularJS, It is better to not include the jQuery file in your page (until it is really necessary) because with AngularJS $http service and rich directive it makes jQuery useless. With AngularJS one thing is sure you have not much cleaner and structured code than jQuery.

This was a short AngularJS introduction in the next article we will see the MVC in AngularJS. So keep commenting the topics you want to see in this series of article so I include articles accordingly.

Here is Next Part of this series:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,