What is Asynchronous programming in Javascript

A lot of my friends who are new to javascript find this concept really daunting and it is infact a topic which makes people working in javascript google it again and again . So i will just put it here for your (and my ) reference .

So when we talk about asynchronous programming in javascript , we are nowhere near parallel programming , but can we achieve parallel programming in javascript ?  Well, with HTML5 spec , we can using web workers , but that is actually a browser spec rather then a feature of javascript . Memorize it by heart (as we said during our school days ), javascipt cannot do parallel processing . Its not even meant for it , it is single threaded by design  , which means it works on only one thing at a time .

But this statement that it works only on one thing at a time sometimes feel hard to digest right because some things (setTimeout , ajax , setInterval i am looking at you) just look like executing in parallel . Well because they are. I know i have made you severely messed up , so lets start again step by step .  Lets first state these four things which are our warriors in javascript land :

1) stack

2) queuee

3) webapis

4) event loop

They are a team , so lets understand their strategy . Now , when javascript file is parsed , all functions are pushed in the stack and it executes synchronously . There are certain webapis of browsers like - setTimeout , setInterval , ajax calls which are outside the javascript runtime engine. they are in the browser and run in sort of a different thread (remember javascipt runtime engine is single threaded) . By running i mean performing their only job, in case of setTimeout , setInterval , running a timer . After completing their task , their callback functions are pushed to the queue , not automatically executed otherwise its effects would appear suddenly in the middle of your code execution . Wherever you see a callback function associated with an event , automatically infer that the function will first be pushed to the queue . After the stack is empty and the javascript engine has nothing to do, the items in the queue would be pushed in the stack and executed synchronously  .

But who pushes these functions from the queue to the stack , who else our silent warrior the event loop .  Now this guy never sleeps , it runs over and over again, hence the name loop, to check the stack and the queue .

Events like onclick , onmouseup etc etc also execute outside the javscript runtime and its callback functions are also pushed into the queue .

Webworkers are a little different as the javascript code inside the web workers are run in a different thread , also called a worker thread .  This thread is not necessarily like the main thread because it does not have access to the window object , cannot access the DOM . It is like a backup knife of a soldier . It is not what he attacks with first , but it definietly increases the damage .

So web workers are just for executing large javascript functions (like complex algorithms ) and return the result in form of messages whose handlers again first go into the queue .

So this is my short take on asyncronous javascript . Hope it helps .

A simplistic guide to start GRUNT

Lets talk about GRUNT - the Task Runner today .  Now, some of you guys would be like .."Woo i am outta here " because yes, grunt has been hyped as a somewhat mysterious feature about which some people think that they are better off without it .
  But if you invest few hours of your life learning it, you will surely save few weeks at the least .
Now, what is grunt and what does it do ? It is an automating tool which is an indisposable particularly if your creating an app for production . You ask why!! because it provides a great API to do tasks like minification , concatenation and almost every task you can think of for which otherwise you would have written hundreds of lines to do  ..

Still confused ? Lets explore it a bit ..

Grunt is built upon Node . What is Node ? Node is an open source , runtime environment which uses the V8 javascipt engine, thus its applications are written in javascript.
V8 javascript engine is used in chrome browser  , so basically they have taken the browser's skill and added it to desktops and servers , so that javascript runs everywhere .
So you need to have Node installed in order to work with grunt , grunt is installed using the npm command :

 npm install grunt --save-dev

adding parameter -g(globally) will do install grunt but  it will not run grunt as you need to have a local copy of grunt for each project you have .  --save-dev will add it to your package.json file inside "devDependencies": { } . If you ask what is devDependency , follow this link

After this  you have to install grunt-cli :

 npm install -g grunt-cli

It is the command line interface for grunt . This will install grunt-cli module in /usr/local/lib/node_modules . If you want it locally in your project folder, remove the -g (globally) . The job of  grunt-cli does is that it runs the grunt installed next to your Gruntfile .  Now, if you had installed grunt-cli and not installed grunt locally , you would get the following error on typing 'grunt' in your :

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

Finally, you need to create a 'Gruntfile.js' manually , which will contain the grunt config and tasks and everything grunt related .
This completes the bare minimum installation task , now you will see the following files in your project directory :

node_modules
        |____grunt
        |____<other modules if you have installed>
package.json
Gruntfile.js

So, lets begin with writing grunt tasks already .  Every thing you write in grunt should be inside a wrapper function :

  module.exports=function(grunt){};

people familiar with node will instantly feel relieved , as this is the standard syntax for exposing node module  to other files . Starting with the basics , lets create a grunt task and run it . Lets create a grunt task ,that prints Hello World .
The syntax for creating a grunt task is 'grunt.registerTask(taskName,taskList)' and grunt.registerTask(taskName,taskDescription,taskFunction) , in our case we will use later one.

module.exports= function(grunt){
grunt.registerTask('firstTask','This is the very first task',function(){
      grunt.log.writeln("Hello World");
}
}


you will get the following output when you type 'grunt firstTask' in your terminal:

Running "firstTask" task
Hello World

Done, without errors.

If you specify the task name as default , the task will run if you just type 'grunt' in your terminal. 

You can also define many sub-properties and run them all using grunt.registerMultiTask . The name itself is verbose enough , we can run multiple tasks with it . Before, we discuss that ,its a good time to talk about grunt.initConfig . This takes an object, which  is used to set the configuration required for your tasks :

grunt.initConfig(configObject);


Lets assume you want to run a multi task 'routine' which has sub tasks : eat , sleep , code .

Gruntfile.js 

module.exports = function(grunt){
grunt.initConfig({
  routine: {
    eat: 'Time to eat',
    code: 'Time to code',
    sleep: 'Time to sleep',
  }
});
grunt.task.registerMultiTask('routine', 'Log stuff.', function() {
  grunt.log.writeln(this.target + ': ' + this.data);
});
}


Output:

$grunt routine

Running "routine:eat" (routine) task
eat: Time to eat

Running "routine:code" (routine) task
code: Time to code

Running "routine:sleep" (routine) task
sleep: Time to sleep

Done, without errors.

You can also read files and configure tasks using there content . For example, if you want to assign the name of your project (which is stored in the name property of your  package.json file ), to the code property of the routine task , you simply have to first read the file :

pkg=grunt.file.readJSON('path/package.json');


and assign its name property value to code 

code: '<%= pkg.name %>' 


'<%= %>' is used to evaluate the values of properties  you create.

To run tasks(plugins) from vendors, you will have to download using npm , and load them in your Gruntfile , suppose you want to use the uglify task(the task for minifying your files) 

Installation :

npm install grunt-contrib-uglify --save-dev


packages with '-contrib' in them are built by the grunt team themselves .

in your Gruntfile :

grunt.loadNpmTasks(grunt-contrib-uglify);
and configuration is to be written inside grunt.initConfig :
grunt.initConfig({
uglify: {
        files: {
          'dest/scripts/scripts.min.js': [
             'src/scripts/scripts.js'
           ]
         }
     },
})


If you want to load external libraries in your gruntfile , you can use require(' library name') , as is written in nodejs. It will find and load the library from node modules .  

Till now, i had specified only a few basic methods which are used in almost every project. All of these methods are defined in different subobjects of grunt but are also exposed to grunt object directly for convenience. Like i used grunt.initConfig , but this method actually belongs to grunt.config API , with the name  grunt.config.init . 

I will wrap up this post with a mere definition of all the APIs , you can have a detailed look at them from the grunt site .

1) grunt.config : This API lets us access and set project specific configuration in our gruntfile. We     explored the grunt.config.init(alias: grunt.initConfig) . 
2) grunt.event : This API lets us configure listeners for events . Grunt itself does not emit any events uptill now .
3) grunt.log : This API lets us output text to the console. We used one of its methods  'grunt.log.writeln' in this post 
4) grunt.fail : This API lets us display error messages when something goes wrong in our grunt tasks and and it will abort grunt . We can use --force command line option to continue running grunt if we used grunt.fail.warn 
5) grunt.file : This API exposes different methods to do file manipulation like create, read,write , copy, paste . We used one of its methods  'grunt.file.readJSON'  in this post
6) grunt.option : This is used to pass paramteres across different tasks , and also to read parameter you set on your terminal while running grunt . If you had specified  the parameter '--ranBy=Aakash' in your terminal ,  grunt.option('ranBy') will return Aakash
7) grunt.template: This API exposes methods to process template strings manually
8) grunt.task: This API registers, runs and loads tasks . We used grunt.task.loadNpmTasks (grunt.loadNpmTasks) and grunt.task.registerTask( grunt.registerTask),                     grunt.task.registerMultiTask(grunt.registerMultiTask) in this post .
9) grunt.util : This API provides miscellaneous utilities for our gruntfile and tasks .

If you could make out something from this post , then GRUNT is now a slave at your disposal :) 

Transclude:'element' demystified

Transclusion is no doubt a very confusing topic in AngularJS. It has two ways of implmentation :

1) transclude: 'true'
2) transclude: 'element'

as far as transclude: 'true' goes, one can grasp it with little effort but transclude: 'element' seems like a lot of work .

So, what thus transclude:'element' do ?

It transcludes the whole element ,i.e, it copies the content inside the directive as well as the directive tag  itself and places one or more copies of it with the correct scope .

The transclusion is achieved via transclusion function unlike the more simpler ng-transclude in case of transclude: 'true' .
For a quick review of transclude:'true' , to achieve transclusion , we included <ng-transclude> wherever we wanted our element to appear inside the 'template' property like :

transclude: 'true',
template: '<some tags here><div ng-transclude><some tags here>',


but when we do  transclude: 'element', we cannot use a template , so we can't  ng-transclude it , so instead, as i just mentioned , we will use transclusion function . Transclusion function is simply a link function , which is returned after compiling the transcluded elements .
To give you an overview of how transclusion is achieved by the browser, the flow is as follows :

var elementsToTransclude = directiveElement.contents();
directiveElement.html(' ');
var transcludeFn= $compile(elementsToTransclude);


So, basically , we are getting the contents of the element containing the directive which has transclusion enabled in the first line and storing them in a variable . Then we are removing the contents  of the element from the DOM . In the third line , we are compiling the variable which has the contents of the element and producing the transclusion function (transcludeFn) .

This function is given as the fifth parameter of 'link' function . It was earlier used in 'compile' function as well but has become obsolete now .

link : function(scope, element, attributes, controller, transcludeFn){}

This Transclude function can accept a scope and a call back function , and this function returns a  clone of the transcluded element instead of the original element  like :

transcludeFn(scope,function(clone){});

This callback function is synchronous not asynchronous . 
Now, its important to understand that this transcludeFn places the transcluded element and the location where you want to place can be achieved by Jquery style DOM traversal and modification . Like if i want to put the transcluded element after the 'element' , which is the second parameter of the link function , i can simply do :

element.after(transcludeFn());


Or i can attach a clone of the transcluded element to the DOM  :

transcludeFn(function(clone){
element.after(clone);
})


In the above two examples of transclusion, the transcluded elements get an inherited scope from the parent scope . Now there is an element of confusion here . The parent scope i am referring to is the original scope not the scope of the directive which has transclusion enabled.
  Let me give an example :
suppose i  have done transclude :element for my custom directive

note that i have isolated the scope of the directive , so in normal sense , anything inside this directive should not inherit from the parent controller scope

app.js :

var app=angular.module('mainModule',[]);
app.controller('mainController',function($scope){
 $scope.Var='Hello I am you father';
});
app.directive('customDirective',function(){
return {
        restrict: 'A',
        scope: {},
        transclude: 'element',
        link: function(scope,element,attrs,controller,transcludeFn){
        transcludeFn(function(clone){
        element.after(clone);
      });
}
}
});


and in my html

index.html:

    <body ng-app="mainModule">
     <div ng-controller="mainController">
       Fathers scope is : {{$id}} 
      <div custom-directive>Hello People Socpe id is : {{$id}} and i am inherited from:                                 {{$parent.$id}} {{Var}}</div>
     </div>
     </body>

{{$id}} is a very neat way to get  the scope id .
{{$parent.$id}} gives the scope id of the parent scope .
i have used {{Var }} in the transcluded element , which is defined only in the parent controller .

So , now in my browser,  i can see :

Fathers scope is : 2
Hello People scope id is: 4 and i am inherited from : 2 Hello i am your father .

Did you see that , did you see that ? That guy is inheriting . 'Var' is being fetched from the parent controller 'mainController' , even though the directive has isolate scope . This behaviour of transclude element is desirable to avoid conflicts between scopes,scope leaking .

Now getting back to the features of transcludeFn , though the default scope of transcluded elements is like the one i mentioned above, you can also provide your own custom scope to it like :

transcludeFn(scope,function(clone){
});


so in the above case, i gave the first parameter as scope, which is also the first parameter of the link function , so you guessed it right , we are assigning it the scope of the custom directive . And since the directive has isolate scope, it will not read any properties from the parent scope and that {{Var}} should not evaluate , since it is not visible now to the transcluded element scope . Right?  Yes ofcourse .

Our view is now :


Fathers scope is : 2
Hello People scope id is: 3 and i am inherited from : 2


Dont get confused by that line 'and i am inherited from : 2', since i used $parent in that and you can access the immediate parent in isolate scopes through $parent , which may sound confusing to some .

Now, lets talk something about the compiling and linking of transcludeFn .

when you do something like :

transcludeFn(scope, function(clone){
element.after(clone) // this is compiled but not linked yet 
}) 


and when you do something like :

var transcluded=transcludeFn();
element.after(transluded) // this is compiled and linked .


So, what is its importance . One is that, if you want to clone the transcluded element several times , like in the case of ng-repeat , you hve to insert the clones into html before linking . They will have individual scopes of their own , again like in ng-repeat ..

Lets further extend our app.js above

var app=angular.module('mainModule',[]);
app.controller('mainController',function($scope){
  $scope.Var='Hello I am you father';
});
app.directive('customDirective',function(){
  return {
    restrict:'A',
    scope:{},     
    transclude: 'element',
    link: function(scope,element,attrs,controller,transcludeFn){
      for (var i = 5; i >= 0; i--) {
      trscluded=transcludeFn(function(clone){
         element.after(clone);
      });
    }
}
}
});

Here you can see we are doing five iterations of the for loop and embedding a clone in our html for each iteration . every clone has its own scope id.

Our view now :

Fathers scope is :2
Hello People Socpe id is : 8 and i am inherited from: 2 Hello I am you father
Hello People Socpe id is : 7 and i am inherited from: 2 Hello I am you father
Hello People Socpe id is : 6 and i am inherited from: 2 Hello I am you father
Hello People Socpe id is : 5 and i am inherited from: 2 Hello I am you father
Hello People Socpe id is : 4 and i am inherited from: 2 Hello I am you father

This happens because we are inserting the html before linking, we wont be able to add clones, if we have already  linked the element, like , if we do

var app=angular.module('mainModule',[]);
app.controller('mainController',function($scope){
  $scope.Var='Hello I am you father';
});
app.directive('customDirective',function(){
  return {
    restrict:'A',
    scope:{},     
    transclude: 'element',
    link: function(scope,element,attrs,controller,transcludeFn){
      for (var i = 5; i >= 0; i--) {
         element.after(transcludeFn());
      }
}
}
});

we will only get a single element in our html :

Our view now :

Fathers scope is :2
Hello People Socpe id is : 8 and i am inherited from: 2 Hello I am you father 

There are many complex implementations of transclde: 'element'  , but as an introduction and understanding to transclude: 'element' , this can get you going .
Cheers .

What is a prototype based language in terms of javascript

Today i was going through the basics and since switching from a class based language to a prototype based language can be a a little tricky , i will leave this post here.

Now. What the wiki says :

Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as prototypalprototype-oriented, classless, or instance-based programming. Delegation is the language feature that supports prototype-based programming.


So , what we can understand that in a prototype based language , objects are created by cloning existing objects(prototypes)  and adding your own properties to it .Actually, in javascript, when  we are creating an object, we are always creating a clone of an existing object .
var o= {a:1,b:2};

Now, this object inherits from a base object in javascript called Object.prototype which has its own methods and properties . Infact , this object  also inherits from the topmost base  object - 'null' , yes , null ( i am not sure if i should call this an object or not , but i like to think it this way for consistency in the model ) .

So, if you give console.log(o.hasOwnProperty) , you will see a function definition in the console :
function hasOwnProperty() { [native code] }


which means that you have inherited properties from Object.prototype and hasOwnProperty is one of its methods .

 So , basically :
0---> Object.prototype -----> null 


Similarly Arrays inherit from Array.prototype and functions inherit from function.prototype which have their own methods and proprties  and both of these inherit from null . 

So , what if we want to create an object from scratch without inheriting from anything. 
Yes, you guessed it right we will inherit from null and give our own properties to it . 

var cleanObject=Object.create(null);

cleanObject.pi=3.14;

So you can see cloning(inheritance) is going on everywhere . And unlike class based language , there is no separate object definition and instance ,i.e, usually in class based languages, object definition does not occupy memory but in javascript they too occupy memory . 
Suppose you  create a function , and it is both an object definition and instance . like :
function hello(){
console.log('Hello World');
}
hello() // working as an instance 
var hi = new hello() // working as an object definition


Which means that there is no explicit class , objects inherit directly from other objects through properties, called prototypes in javascript . So if you define and attach anything to the prototype property of an object , then it will be visible to all the objects inheriting from that object . And if you change that definition later in any object , then it will be visible to all objects . like in this example :

var Person = function() {

  this.canTalk = true;

};

Person.prototype.greet = function() {

  if (this.canTalk) {

    console.log('Hi, I am ' + this.name);

  }

};

var Employee = function(name, title) {

  Person.call(this);

  this.name = name;

  this.title = title;

};

Employee.prototype = Object.create(Person.prototype);

Employee.prototype.constructor = Person;

var bob = new Employee('Bob', 'Builder');

var rg = new Employee('Red Green', 'Handyman');

bob.greet();

rg.greet();

Person.prototype.greet=function(){

  console.log('Just for testing');

}

bob.greet();

rg.greet();

So in the above example, we change the greet function, and the change is reflected across all instaces .

And yaa about that last line 'Delegation is the language feature that supports prototype-based programming.' , if you guys are wondering what delegation is , then to sum it up , it is similar to classical inheritance but with much lighter memory footprint invloved and entangles the overly complex hierarchies . Means, you can call any function in context of an instance of another function without considering the hierarchies involved . It simplies inheritance actually . Delegation is primarily achieved in javascript by 'call' and 'apply' .You can use 'call' and 'apply' to call any function inside an instance of a function . 
If you want to learn more about delegation , then you can follow this article . 
So thats all you need to get the feel of a prototype based language . 
Cheers

pipeline of ngModelController

ngModelController is undoubtedly one of the reasons why AngularJS is so awesome . It is responsible for two way data binding , which is what people use when they are asked to display Angular powers. It is the eye candy of Angular .

Yaa i sound like i am in love with it .. Well, yes i am.

Using ngModelController in its usual form ( inside input fields with ng-model) is all easy and fun. All you have to do is give a model value to ng-model attribute and you are good to go..

<div ng-controller="databinding">
<input type="text" ng-model="user" >
</div>
 
.controller('databinding',function($scope){
$scope.user="HiEveryone";
});
And there you have a two way data binding . But the heart pounding situation comes when you want to implement two way data binding on other tags or your custom directive . Yes it looks very complicated at first but once you understand the flow , you get all sorted.
So, what really is the flow .. The flow is :
Model->View

$modelValue->$formatters->$viewValue->$render

View->Model

$setViewValue->$viewValue->$parsers->$modelValue

 These names are methods and properties of ngModelController which you need to take hold of when creating your own custom two way data binding . To access ngModelController, you have to require ngModel , and you will have access to the controller as the fourth parameter in the link function.  
Suppose you have a custom directive with an ngmodel attribute :

<customdirective ng-model="bindvariable"></customdirective>

The directive definition will be :

.directive('customdirective',function(){
return {
require:'ngModel',
link: function(scope,element,attributes,ngModelController)
{
};
};
})
Now,
$modelValue - It is the value in the model , it retrives the value which is in the model.

$viewValue -   Actual string value in the view as given in Angular docs. But it sounds rather confusing to me becuase in your custom directive, unless you do a render, the value is not updated in the view . Yes, i know that obviously you will do render , but what if you give something else to render , like in this code .
Here, in the console, you can see that $viewValue is different and the value displayed in the view is different .

$render- It is called when the view needs to be updated, and yes you have to define a $render, else your view will not be rendered. 

$parsers- As explained in docs , $parsers accept an Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. The functions are called in array order, each passing its return value through to the next. The last return value is forwarded to the $validators collection.
Parsers are used to sanitize / convert $viewValue .
$formatters :  As explained in the docs, It accepts an Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control.


So basically $parsers and $formatters are the workers who modify the values passed between the model and the view , In the example below, you can see that we have added a function in the formatter pipeline which will transform the model value to uppercase . 


function formatter(value) {
  if (value) {
    return value.toUpperCase();
  }
}
ngModel.$formatters.push(formatter);

$setViewValue : According to the docs, It Updates the view value.
This method should be called when an input directive want to change the view value; typically, this is done from within a DOM event handler.
For example input calls it when the value of the input changes and select calls it when an option is selected.
Again , you should understand that it updates the $viewValue and does not update the value in the view which is visible to you . $setViewValue will automatically call the $parsers and $validators pipeline. 
$validators is a simple concept , it is just a  collection of validators which are applied whenever the model value changes. AngularJS Docs are enough to understand it. 
You can see all these in action in the following plunker link 
So, here the 'Change Model' button will activate the Model->View pipeline , and you can see the $formatter in action , it converts the model value to uppercase and the value is rendered to the View using the $render function . 
And if you type in any value in the div element and click anywhere in the screen , it will activate the View->Model pipeline , $setViewValue and $parser is run , and the value is updated in the model in the uppercase form . 
$setViewValue is called inside $apply because we are calling it inside elm.on() , which is jquery . Since it is outside the AngularJS realm, to use any AngularJS feature inside it, we have to run it inside $apply . 

There are hell lot of properties and methods of ngModelController, but my aim with this doc was only to explain the bare minimum which you need to use two way data binding . You can understand the application of other properties and methods once you understand how the controller achieves what it is supposed to achieve. I hope this post eased your pain a bit . 

* Grabs a beer * 


Forms in angularJS (ngFormController)

Forms in angularJS are quite advanced then the normal HTML forms, and they work wonders with ngModelController. ngModelController, along with keeping the model and view in sync( by $formatters and $parsers) also helps in validating the data and checking if the value was changed from its default ( this is achieved by $pristine,$dirty,$valid,$invalid properties and by using the respective css classes) . There are a lot many properties and methods of ngModelController but we will mention these four for simplicity .

ngModelController.$pristine returns true if the value of the input field has not been changed from its initial state .

ngModelController.$dirty returns true if the value of the input field has been changed from its initial state .

ngModelController.$valid returns true if the value of the input field is valid (as the name suggests)

ngModelController.$invalid returns true if the value of the input field is invalid.

Now, a form directive (or ngForm) creates an instance of ngFormController . Each ngFormController does the same thing as ngModelController but for the whole form, instead of only an input element(in case of ngModelController) .

Now, how does it do it? Using the underlying ngModelControllers. Each ngModelController registers itself to its parent form, if there is any. The ngFormController also has the same properties and methods as ngModelController ( except $addControl(), $removeControl() , $setSubmitted() methods ) , so it sets its properties like $invalid,$valid,$pristine,$dirty according to the underlying ngModelControllers (like if any input ng-model field is set to $invalid, then the ngFormController is set to $invalid ) .

You should keep in mind , that any form elemnt creates an instance of ngModelController , like if you write like :
<form name="userForm">
</form>


ngFormController will be instantiated and css classes will be added to them instantly:

In developer tools , you will see

<form name="userForm" class="ng-pristine ng-valid">
</form


Now these properties of ngModelController and ngFormController can be used to do validation and other stuffs . Like , suppose you want to do the validation in a url input field , like show an error text if the url field is empty, and show an error text when the url is not a valid one. These can be very easy as ngModelControllers have built in validation for input types and you merely have to do this::

<form name="userForm" ng-controller="FormController">
<input type="url" name="url" ng-mode="url" required>
<span ng-show="Error(userForm.url, 'required')">url field should not be empty</span>
<span ng-show="Error(userForm.url,'url')">url is not valid</span>
</form>


and in the FormController:
.controller('FormController',function($scope){
$scope.url=' ';
$scope.Error=function(ngModelController,error){
return ngModelController.$error[error];
}
});


So this Error function takes in the ngModelController and the error type. So, how did we reference the ngModelController .
By the 'name' attribute we can reference the ngModelController. Syntax is : <name_of_the_form>.<name_of_the_directive_which_has_ng-model> .
And ngModelController has $error property , An object hash with all failing validator ids as keys.
In this case, the validator ids are 'required' and 'url' .

And you can check the validity of the whole form with "userForm.$error[]". Then we can disable the submit button, or disable a save button or any action which the user performs only when the form is valid, simply by calling a function which checks $valid property of the form .

<form name="userForm">
   <button ng-disabled="cannotSave()"></button>
</form>
.controller('FormController',function($scope){
  $scope.cannotSave=function(){
return $scope.userForm.$invalid ;
}
});


We have seen and understood the behaviour of form attribute in AngularJS , but what about ng-form, and why is it even there when we can achieve everything through form attribute . We missed out one thing, which cannot be achieved by form attributes :--' Nesting of forms' .
Using a form attribute inside another form attribute is invalid HTML , so AngularJS came up with ng-form . We can  nest any number of ng-forms inside form attributes and inside each other .

One very useful usecase is the the use of subforms as reusable components , which will reduce repeated code . Suppose we want to use the above url input form as a reusable component and embed it inside another form . Lets create a simple form which only has a FirstName and LastName input field .

<form name="parentForm">
<input type="text" name="firstname">
<input type="text" name="lastname">
<ng-include src="'urlform'"></ng-include>
</form>


we have included the form with ng-include . Now, the structure of the reusable form will be :

<script type="text/ng-template" id="urlform">
<ng-form name="userForm" ng-controller="FormController">
<input type="url" name="url" ng-model="url" required>
<span ng-show="Error(userForm.url, 'required')">url field should not be empty</span>
<span ng-show="Error(userForm.url,'url')">url is not valid</span>
</ng-form>
</script>


Notice that we have copied the whole code of the url form we had , and just replaced form with ng-form and it did the trick .

Also, we might have fields in a form which needs to be repeated and added dynamically, like the addresses of social networking sites you are active in, because someone has less number of  profiles and someone has more . We need to add fields with an 'Add' button , which will create an input field, and also we need to have validation in each of these fields.
Now, suppose we dont use ng-forms , then we will fully rely on ng-repeat directive , which will repeat the input fields . But each of this input fields dont have any identifier, like a name attribute or something , and we cannot generate  dynamically name attributes through angularJS for input directives .
What we can do in such situation is give an ng-form attribute in the directive which has ng-repeat
<div ng-repeat ="website in user.websites" ng-form="userForm">

Now, this will create a userForm for each each website in user.websites, and we can reference the ngModelController of the ng-model attributes inside this ng-form .

You can see this example from this link here .

So, this is what i had to discuss about Forms in AngularJS. Hope, you could make something out of it, and do give feedbacks .



Scopes in directives of AngularJS

For this blog , you need a basic understanding about custom directives in AngularJS .

Scope is a concept of AngularJS which can be pretty tricky at times, and can get difficult to make sense out of it . Thanks, to some extensions, like batarang , we can check the scope IDs of elements and check which have same or different scope.   All DOM elements that have been compiled by AngularJS have a scope associated  with them. In most cases DOM elements do not have scopes defined directly on them but get their scope from some ancestor element. New scopes are created by directives that specify a scope property on their directive definition object( will talk about that in a short while) .  If we talk about built in directives of AngularJS, then only a few core directives define new  scopes, these are ng-controller, ng-repeat, ng-include, ng-view, and ng-switch. They all create child scopes that prototypically inherit  from their parent scopes.
And when we create a custom directive using app.directive  , which uses a  service called $compile and its provider  $compileProvider , we also create a scope(or not) based on our requirements. If you are wondering what this $compile is, $compile is at the heart of AngularJS machinery and can turn HTML strings (with directives and interpolation expressions) into live DOM.  We can add our own functionality to this compilation process using the compile property like ::

app.directive('myDirective',function(){
return{
compile: function(element,attrs){
// here we can add functionality to be run during the compile phase
}
}
})

I will tell in detail about the compile (and about creating a custom directive as a whole) in a later blog.

Now, getting on with the scope thing, the directive service has a scope property, which defines the scope of the directive which we are creating ..
There are, three options for the scope directive ::

app.directive('myDirective',function(){
return{
scope: true //or scope: false //or scope:{}
}
});

scope:false is the default value. Now, what does  these actually mean . 
Put in simple words, scope:false , means that you dont want a separate scope for this directive. It is also called 'shared scope' . Shared scope simply means that the directive works with the same scope that is already available for the DOM node where the directive appears without creating a new one. 

scope: true,  means 'inherited scope' , 
In this case, a  new scope is created for our directive, but it inherits all the properties of the parent scope through JavaScript's prototypical inheritance: when the directive accesses a property on it's new scope, the property is first searched on the current scope and if it's found then it's value is returned, otherwise, if it's not found, the same property name is searched in the parent scope and that value is returned (the search traverses all the parents until the property is found or until there are no more parents); if a value is assigned to a property on the new directive's scope and the same property already exists in the parent, accessing the property value directly in the new scope will in fact override the parent's property value and any change to the property in the parent will not be propagated anymore to the child scope.

and, the one used most commonly is  scope:{ }, which means isolated scope .
As its name suggests, it is an isolated scope, which has no connection with the parent element in which it resides, though it can access the parent element by $parent, but its functionality is not affected by the scope of the parent in which it resides.

We can however have connection between the isolated scope, and the parent scope in terms of accessing data or methods or enabling data binding. There are three types of interface we can specify
between the element's attributes and the isolated scope: interpolate (@) , data bind (=) , and expression (&) .

The various options available with the scope are ::
scope:{
key1:'@attribute1',
key2:'=attribute2',
key3:'&attribute3'
}

These are written in form of key: value pairs .The key is the name of the field on the isolated scope. The value is one of @ , = , or & followed by the name of the attribute on the element. If you omit the attribute names::

scope:{
key1:'@',
key2:'=',
key3:'&'
}
then key1, key2, key3 will be taken as the attribute names.. Now, i am having the temptation to blurt out the whole directives concept here, but i will refrain myself :P and talk about the directives(along with the scope options above) in a separate blog, to make this blog to the point :) .

Ok, so  let me give examples of all these scope variations in terms of scope ids::

Shared Scope:::

Parent Scope Id: 002
Directive Scope Id: 002
(they are bound to the same scope)

Inherited Scope::

Parent Scope Id : 002
Directive Scope Id : 003( but is inherited from the parent scope)

Isolated Scope::

Parent Scope Id: 002
Directive Scope Id : 004(is completely isolated from the parent scope)


Now, what if multiple directives with different scope variations appear on a single HTML DOM node.
The way they interact with each other changes a little bit in these cases..


   1) If there are only  shared scope directives, then they will behave as usual, and share the parent scope.

  2) If there are only inherited scope directives, then they will all be bound to a single scope inherited from the parent scope.

  3) If there are mix of shared and inherited scopes, then the shared scope will also behave as inherited scope , and all these directives will be bound to a single inherited scope .

  4) There can only be a single isolated scope directive on a DOM node .

  5) If you mix one isolated scope directive to any bunch of directives mentioned in 1)  2) 3) , then others will behave as mentioned in these points, along with one isolated scope created for this  isolated scope directive.

So, this is all i had to talk about scopes . Thanks, for giving it a read and do add additional info on these :)