AngularJS Controller Tutorial with Example

angular-js-logo

Let us talk about one of the AngularJS’s most useful feature which helps in making awesome single page applications in JavaScript – The Controller. This tutorial is part of series of tutorials on AngularJS where we shall touch different aspects of Angular and its features. In our last tutorial we saw Introduction of AngularJS and also created a Hello World example using Angular. Controllers are nothing but plain JavaScript functions which are bound to a particular scope. Don’t worry if this sounds gibberish. Shortly this all will make sense once we create a small Hello World using controller. Controllers are used to add logic to your view. Views are HTML pages. These pages simply shows the data that we bind to them using two-way data binding in Angular (Note: Two-way data binding is explained in previous tutorial). Basically it is Controllers responsibility to glue the Model (data) with the View.

1. What are Scopes?

Before we get into Controllers let us understand Scopes. Scope is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view. Scope uses Angular’s two-way data binding to bind model data to view. Imaging $scope as an object that links Controller to the View. It is controllers responsibility to initialize the data that the view needs to display. This is done by making changes to $scope. Let us see a small Hello World application to understand $scope.

<!DOCTYPE html> <html ng-app> <head> <title>Hello World, AngularJS - ViralPatel.net</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> </head> <body> <div ng-controller="ContactController"> Email:<input type="text" ng-model="newcontact"/> <button ng-click="add()">Add</button> <h2>Contacts</h2> <ul> <li ng-repeat="contact in contacts"> {{ contact }} </li> </ul> </div> <script type="text/javascript"> function ContactController($scope) { $scope.contacts = ["[email protected]", "[email protected]"]; $scope.add = function() { $scope.contacts.push($scope.newcontact); $scope.newcontact = ""; } } </script> </body> </html>
Code language: HTML, XML (xml)

1.1. Online Demo

Play on JSFiddle – http://jsfiddle.net/viralpatel/aLDJJ/ In above demo, just write something in the textbox and press Add button. This will add whatever you type in textbox in an array. The content of array is displayed below in a list. First thing you should note in demo is the attribute ng-controller.

1.2. ng-controller

This attribute defines a Controller to be bound with the view. In this case we defined a controller called ContactController in DIV using ng-controller attribute. Thus whatever we put inside that DIV, the ContactController will have its influence on it. ContactController is nothing but a plain vanilla JavaScript function. In the demo we defined it as function. Also see the definition of ContactController function. There is an object $scope which we pass as an argument. This object is used to bind the controller with view. When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection (More on dependency injection in coming tutorials). For now just note that the $scope object is created by Angular and injected in this controller function.

1.3. ng-repeat

Notice how we displayed a list of contacts using an attribute ng-repeat.

<li ng-repeat="contact in contacts">{{ contact }}</li>
Code language: HTML, XML (xml)

ngRepeat is one of the most used AngularJS attribute. It iterate through an array and bind the view with each element. So in our example it creates <li> tag for each item within contacts array. ngRepeat takes expression as argument. In our case “contact in contacts” where contact is user defined variable and contacts is an array within $scope. In our final demo in this tutorial, we will use ng-repeat to iterate through an array of objects and paint each property in a table.

2. Initial state of a scope object

Typically, when you create an application you need to set up an initial state for an Angular scope. In our case we need initial state to be list of contacts. On $scope object, we defined an array called contacts:

$scope.contacts = ["[email protected]", "[email protected]"]
Code language: JavaScript (javascript)

When Angular initialize this function (ContactController), it automatically creates this array and binds it in $scope object. Then in our view we display the array using ng-repeat attribute. Thus, $scope provides us with a way to pass/retrieve objects from Controller to View and vice-versa.

2.1. ng-click

It is also possible to define functions on $scope and use the same in View. In our demo, we created a function add() on $scope and use it on Add button click:

$scope.add = function() { ... }
Code language: JavaScript (javascript)

The function add() is bound to Add button using an attribute ng-click. ng-click binds the click event on the button or link or any clickable element with the function that is defined within $scope. So in this case, whenever Add button is clicked, the add() method on $scope will be called. In add() method we add (or push) a string in contacts array. This is the string that user types in textbox. Note that we bind textbox using ng-model attribute.

<input type="text" ng-model="contact" />
Code language: HTML, XML (xml)

This textbox’s value we got in $scope.contact as we bind it using ng-model attribute. Pretty nice, isn’t it!!

3. How to define a Controller

So we got some basic idea of what Controllers are. Just plain vanilla JavaScript functions that we add in an Angular application to add some business logic and bind the view with model. In the above demo, we defined controller as JavaScript function. While this is the easiest way to define them, but is certainly not advisable one. If your application grows, soon you’ll have bunch of controllers lying here and there in code polluting the JavaScript namespace. So instead of defining controller as:

function ContactController($scope) { //... }
Code language: JavaScript (javascript)

We should define Controller within Modules.

3.1. AngularJS Modules

So what-the-heck are modules? Well, modules are the logical entities that you divide you app in. So your app can contain several modules (like Transaction, Report, etc.). Each module represent a logical entity within the app.

angularjs-app-modules-controllers-view

Furthermore, each modules have several Controllers. As referred in above diagram, a module can contain one or more controllers and views. We haven’t touch based on Views. We will see how each module can be linked with view using Routing in AngularJS in our next tutorial. For now just assume that each controller has one or more views linked to it. So in this case, we can add one or more controllers to a module. Let us check the syntax to create a module and add controller to it:

var myApp = angular.module('myApp',[]); myApp.controller('ContactController', ['$scope', function($scope) { $scope.contacts = ["[email protected]", "[email protected]"]; $scope.add = function() { $scope.contacts.push($scope.contact); $scope.contact = ""; } }]);
Code language: JavaScript (javascript)

In above example we created a module called myApp using angular.module() method. Then we added a controller ContactController to this module. This is just an alternate way of defining a controller but recommended one. Notice how controller is declared using myApp.controller() method. We passed an array to this method. First argument of array is string ‘$scope’ and next is the function itself that represent ContactController. We explicitly told Angular that we have one argument (dependency) to our ContactController which is $scope. This is useful when you Minify or obfuscate JavaScript for production release. In that case the argument $scope might be renamed to $s, but because we defined string ‘$scope’ as first argument, Angular is aware that first dependency to this controller is $scope object. To cut it short, always stick to the above way of defining controllers.

4. Nested Controllers

We can declare the scope of controller in our HTML page using ng-controller attribute. For example:

<div ng-controller="CarController"> ... </div>
Code language: HTML, XML (xml)

We can declare number of controllers and nest them within each other. For example:

<div ng-controller="CarController"> My name is {{ name }} and I am a {{ type }} <div ng-controller="BMWController"> My name is {{ name }} and I am a {{ type }} <div ng-controller="BMWMotorcycleController"> My name is {{ name }} and I am a {{ type }} </div> </div> </div> <script> function CarController($scope) { $scope.name = 'Car'; $scope.type = 'Car'; } function BMWController($scope) { $scope.name = 'BMW'; } function BMWMotorcycleController($scope) { $scope.name = 'BMWMotorade'; $scope.type = 'Motorcycle'; } </script>
Code language: HTML, XML (xml)

4.1. Online Demo

Play on JSFiddle – http://jsfiddle.net/viralpatel/gWz4K/ In above demo, notice how each nested Controller’s scope override the scope of parents controller. First we defined a controller CarController which defines two variables name and type within scope. Next BMWController is nested within CarController using ng-controller attribute. BMWController overrides name attribute and change it to BMW. It does not change type attribute so type attribute is still Car. BMWMotorcycleController is the inner-most controller defined within controllers hierarchy. It overrides both name and type attribute of scope. This way you can nest one controller within another and take advantage of parent controllers attributes whenever needed.

5. Inheritance in Controllers

In order to take advantage of inheritance of scope in Nested controllers, one has to define Controllers one into another using ng-controller attribute. Sometimes you don’t want to define controllers like this but still want to use power of inheritance within controllers. May be you want to put common logic into BaseController and use it in all the child controllers. In order to achieve this, we must use $injector object that AngularJS provides.

<div ng-controller="BMWController"> My name is {{ name }} and I am a {{ type }} <button ng-click="clickme()">Click Me</button> </div> <script> function CarController($scope) { $scope.name = 'Car'; $scope.type = 'Car'; $scope.clickme = function() { alert('This is parent controller "CarController" calling'); } } function BMWController($scope, $injector) { $injector.invoke(CarController, this, {$scope: $scope}); $scope.name = 'BMW'; } </script>
Code language: PHP (php)

5.1. Online Demo

Play on JSFiddle – http://jsfiddle.net/viralpatel/WCZcZ/ We define two controllers, CarController and BMWController. CarController defines two attributes name and type on $scope and also defines one method clickme(). BMWController just override name attribute. Notice that it does not have name and clickme defined within its body. These attributes are defined by parent controller in this case CarController. Within BMWController, we initialize CarController and bind it into current scope using $injector.invoke() method. Once this is done, notice how in HTML page the BMWController points to its parent’s attributes.

6. End to end application using AngularJS Controller

Let us apply the knowledge that we acquired so far and create a ContactManager application. Following are some basic requirements of this application:

  1. User can add new contact (name, email address and phone number)
  2. List of contacts should be shown
  3. User can delete any contact from contact list
  4. User can edit any contact from contact list

Following is the HTML code which defines a FORM to save new contact and edit contact. And also it defines a table where contacts can be viewed.

6.1. The HTML

<div ng-controller="ContactController"> <form> <label>Name</label> <input type="text" name="name" ng-model="newcontact.name"/> <label>Email</label> <input type="text" name="email" ng-model="newcontact.email"/> <label>Phone</label> <input type="text" name="phone" ng-model="newcontact.phone"/> <br/> <input type="hidden" ng-model="newcontact.id" /> <input type="button" value="Save" ng-click="saveContact()" /> </form> <table> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Action</th> </tr> </thead> <tbody> <tr ng-repeat="contact in contacts"> <td>{{ contact.name }}</td> <td>{{ contact.email }}</td> <td>{{ contact.phone }}</td> <td> <a href="#" ng-click="edit(contact.id)">edit</a> | <a href="#" ng-click="delete(contact.id)">delete</a> </td> </tr> </tbody> </table> </div>
Code language: HTML, XML (xml)

Just note that we have used ng-model, ng-click and ng-repeat attributes from Angular so far. To add life to this application, we add following JavaScript code.

6.2. The JavaScript

var uid = 1; function ContactController($scope) { $scope.contacts = [ { id:0, 'name': 'Viral', 'email':'[email protected]', 'phone': '123-2343-44' } ]; $scope.saveContact = function() { if($scope.newcontact.id == null) { //if this is new contact, add it in contacts array $scope.newcontact.id = uid++; $scope.contacts.push($scope.newcontact); } else { //for existing contact, find this contact using id //and update it. for(i in $scope.contacts) { if($scope.contacts[i].id == $scope.newcontact.id) { $scope.contacts[i] = $scope.newcontact; } } } //clear the add contact form $scope.newcontact = {}; } $scope.delete = function(id) { //search contact with given id and delete it for(i in $scope.contacts) { if($scope.contacts[i].id == id) { $scope.contacts.splice(i,1); $scope.newcontact = {}; } } } $scope.edit = function(id) { //search contact with given id and update it for(i in $scope.contacts) { if($scope.contacts[i].id == id) { //we use angular.copy() method to create //copy of original object $scope.newcontact = angular.copy($scope.contacts[i]); } } } }
Code language: PHP (php)

First thing to note, we created a variable uid and set its initial value to 1. This variable is used to generate unique ids for each new contact we save. In real life application you may want to do this at backend. We defined one controller ContactController. This controller defines following objects within $scope:

Scope objectTypeComment
$scope.contactsArrayArray to store contact objects. In real life app, this should be maintained at server-side.
$scope.saveContactJavaScript FunctionSaves the newcontact object within contacts array. Check if contact is new or is being updated
$scope.deleteJavaScript FunctionDelete the contact object from contacts list based on id specified
$scope.editJavaScript FunctionUpdate the contact object in contacts list based on id specified

6.3. Online Demo

Play on JSFiddle – http://jsfiddle.net/viralpatel/JFYLH/ You can add new contact using the above form. Once new contact is saved, the list showing contacts will be updated. Each contact can be edited and deleted. You got the gist :)

That’s All Folks

AngularJS is fun.. isn’t it. We saw what Controllers are. How to create Controllers and use $scope object to bind model values with the views. We went through AngularJS attributes such as ng-controller and ng-repeat. Also we saw how Nested controllers and inheritance in controllers work. Finally we created a ContactManager application using AngularJS. We are not done yet!! Stay tuned for next tutorial where we will explorer world of Views and Routing using AngularJS :) Update: Next tutorial is published. Read now AngularJS Routing and Views Tutorial.

Get our Articles via Email. Enter your email address.

You may also like...

126 Comments

  1. Mike Erickson says:

    If you edit a contact, the delete the contact being edited, click saving doesn’t recreate contact. My thinking, clear the new contact form after delete action to avoid confusion for future users. Just shows a little more attention to detail

    • Hi Mike, Thanks for pointing that out :) I have updated the demo.

  2. Arun Kamble says:

    Hi Viral,

    Thank for the tutorial. I knew AngularJS a bit, but your tutorials are help me a lot.
    Waiting for your new tutorials on “world of Views and Routing using AngularJS”

    Best Regards,
    Arun

  3. prem says:

    You write well. Good, easy to understand AngularJS tutorial. Eagerly waiting for next installment.

  4. Habibur Rahman says:

    Very nice article and nice explanation. Eagerly waiting for the next part.

  5. raf says:

    Hi,

    http://jsfiddle.net/viralpatel/aLDJJ/

    When we add a contact it does not show in the output.
    This is because, the model name is wrong in the controller function.
    It should be
    $scope.contacts.push($scope.contact);
    instead of
    $scope.contacts.push($scope.newcontact);

    Regards,
    Raj

  6. Ravi says:

    Hey Viral,

    Excellent demos. Looking forward few more examples with new tags/mode/controllers.

  7. waagraphics.com says:

    nice blog for me ..i love and thank to author

  8. Snesh says:

    Angularjs is new for me. Nice article ..thx a lot.

  9. kumar says:

    hai, tutorial very nice.
    develop angularjs application using angularstrap. what are the files add to the index.html. my application is click button and popup the calendar.

  10. Ahmed says:

    Great tutorial. Actually the first tutorial I’ve seen that really made me understand Angular so very well done! Can’t wait for the next one!

  11. Ankur Raiyani says:

    Great, article !!!
    Thanks a lot for sharing this.

  12. Karumbasalam G says:

    Nice article… it has good explanation… really appreciating your work on this article.. great…

  13. alanb says:

    Thank you for the excellent tutorial and examples.
    It would be really useful if you could explain/show how to populate the initial contacts from a Rails or sqlite backend.
    Looking forward to the next tutorial.

  14. Deepa says:

    I have doubt do i need to include any external file as mentioned in src.
    If Yes please show us the path where we can download.
    Actually its not identifying ng-app.

  15. Deepika Patel says:

    Hello, Viral
    please create demo for getting data from server with $http reqest with the help of defered() and promise(). I want to example.please help…
    Thanks!

  16. Blowsie says:

    Great article, I’m looking forward to the next article you mentioned covering modules, when will this be posted?

    Thannks

  17. Hey, I need help.
    I am working with SQL Server 2008, MVC.NET 4.0 and EF4.0 for a Single Page Application.

    I have a form that has multiple dropdownlists (say 5).
    The dropdown gets populated using LINQ query from the database. It returns the list as “items”

    Now in the Front-end I am populating the values in the dropdownlists using ng-model=”item.projectId”

    Now when I submit the form, its quite obvious that the projectId will be posted to the server due to the double-binding nature of ng-model directive.

    I want to get the selected (user selects while filling up the form) values collectively (possibly into an array ) and send it to the controller.cs file where there an array to consume those values and store that in the table. Can anybody give me tips on this?

  18. Balaji says:

    Hi, it’s very useful. But I have one small doubt. These controllers are present onl in the js file, how will it interact with back end system. Because generally we need these values to be passed to the java code to pass them to the back end system. Can anybody help me with general angular MVC thing. In simple laymane manner. Thanks in advance.

  19. Jonathan says:

    VERY nice article. Section 5 with Ctrl inheritance is exactly what I spent all of yesterday searching how to do. Thanks a lot!

  20. Phan mem says:

    Thanks for the tutorial. Can you write a tutorial about ajax update data to server? I’m having problem with that and don’t have much experience.

  21. sanjay says:

    If suppose i want to write the same application with model which is written in C#, Then how our angularJS template will communicate. Since I am using AngularJS with MVC 4, and I am confused with the structure of entire application. Let me know the actual flow with the sample demo.

    I mean, I want how can you demonstrate if I write model in C#, and templates written with help of AngularJS.

  22. sanjay says:

    Let me make it more clear question:
    I have some questions using MVC4+ Angular JS :-

    How can we write our model in C# and communicate with AngularJS Template.
    Since I am using AngularJS with MVC 4, and I am confused with the structure of entire application. Let me know the actual flow with the very simple demo.

    I know, writing model in C# , doesn’t recommend by AngularJS. but how server side model handle by AngularJS template. Lets say, for Authentication or Authorization we need to write our model in Server side, so how this server side Model will be handle by AngularJS template.

    It will be better if any one can give the answer with small sample application, since I did not find clear sample code anywhere.

    I mean, I want how can you demonstrate if I write model in C#, and templates written with help of AngularJS.

  23. alia says:

    Hi ! thanks for the tutorial. but i tried running 6.1 & 6.2 , but i received an error. could anyone help me? im still new with angular =/
    error that i received was:

    Error: Argument ‘ContactController’ is not a function, got undefined
    at Error ()

    i need help please. thanks in advance!

  24. saurabh shah says:

    Vira, simplicity of language for explaination matters a lot.
    *Awaiting your next version with Router & RouteProvider details with same sense of simplicity for multi-page application demo.

  25. Dom says:

    This was a great for a quick refresh, although you state to only use the recommended way of writing controllers, you continue to use the worse method from then on.

  26. Bala says:

    Yet another good article in series.
    waiting for next article…. Hope you post it soon…!!!

  27. Geetika says:

    Thanks for the excellent tutorial.

  28. Ravindra says:

    Hi Mr.Patel, do you have any working CURD example of angularjs, php and mysql working together as a code example.

    Thanks.

  29. Vishavdeep singh says:

    Excellent work. Please correct some grammer mistake in tutorial find word “attribyte” . It should attribute

  30. ravindra says:

    Onclick how to get textbox value using angularjs.

    I’ve tried like this but it is not coming
    Test

    function ClickTest($scope) {
    var bttn;
    $scope.getAlert = function() {
    bttn = angular.element(document.getElementById(‘#inputId’).scope().value);
    alert(bttn);
    }

    }

  31. Dinesh says:

    can you please help me with putting this model into database?

  32. ranadheer says:

    Hi. Nice post. Thank yo. We cal also call one controller from another controller. Look at this post:
    http://coding-issues.blogspot.in/2013/11/call-controller-from-another-controller-angularjs.html

  33. abhijit says:

    He good work. I am also working on angular js and creating few demos that can be used for explain the concepts. your blog help a lot. :)

  34. Wim Praet says:

    I think the json presenting the initial context is wrong (although it seems to work fine). The id key needs to be quoted, see http://stackoverflow.com/questions/949449/json-spec-does-the-key-have-to-be-surrounded-with-quotes .

  35. JeffB says:

    For the online demo in section 6.3, I would love to see the .css and and the html with the css id/class names.

  36. Nitesh says:

    hi viral i had seen ur blog i like this

    i had one query can u please solve this
    :when i click my add button which is residing to textbox it should add me new textbox

  37. Ramya says:

    HI Viral,
    Your tutorials are very easy to understand.

    I have a doubt in this todo app.

    Is it possible to store the data’s locally. i.e Even after refreshing the page todo list should not get erased. Is that possible using angularjs.

    Thanks in advance:)

  38. Prabhath says:

    Very useful for beginners to get an overview :-) Thank you

  39. nir says:

    very nice tutorial:

    how would you add a button to read a local csv file that holds the data name, email, phone ? with multiple lines ?

    that sound hard right ?

    thanks for the example

  40. bc says:

    Hello
    What is the use of the string ‘$scope’ ( not the scope passed in function($scope) ) that is passed in when controller is created inside the module?

  41. lucas says:

    Hello,

    Thanks for this great tutorial.
    It seem to have an error in the jsfidlle version of your first code.
    http://jsfiddle.net/viralpatel/aLDJJ/
    You write
    Email:
    You should have written
    Email:
    For the text typed to be inserted in the list.

  42. Lennart says:

    Moin Moin

    Nice tut, i will try the injector now for the first time :)
    Perhaps you can write something about how to use a controller from directives and factory? Is use a websocket http://clintberry.com/2013/angular-js-websocket-service/ and want to call my controller without a callback…

    lenny

  43. Jijo says:

    Good Sample!

  44. Avik says:

    Well written!

  45. Jju says:

    Hi Viral,

    I was trying your sample code and Id’s are not getting populated in the object. while searching in googel,got to know that hidden is not supported in AngularJs. May I know it is correct, then how its worked for you ?

  46. Ravi says:

    Good Explanation…….

  47. indra says:

    hi i am trying to create a sample web application using angular js in eclipse.But it shows undefined error for ng-app and other angular js related tags on the page.i went through lot of sites to get over it but nothing could resolve the issue.Please help

  48. Anand Kr Pandey says:

    Thanks a lot for this wonderful work…

  49. Anirban says:

    Very nice article. Helped to clear lot of concepts

  50. khusroo hayat says:

    Thanks a lot a very nice and precise article

  51. Shabin says:

    Excellent tutorials Mr.Patel. Thanks a lot :)

  52. Senthil C says:

    Thanks! Very nice tutorial with nicely laid out examples…keep up the great work!

  53. Duc Hong says:

    Excellent tutorial, especially on the nested controller, keep up the great work

  54. satya says:

    hey Patel ,
    very nice article , angular or in any OOP framework , always better t console the object and study it’s properties / behavior. God Bless

  55. murali says:

    I loved the way you presented it. Nice explanation…

  56. Pradeep Kr. Yadav says:

    Hi Viral,

    Thanks for your Excellent tutorial Carry on…..

  57. Vijay Kumar says:

    Nice article, It is very easy to learn angular js, thanks a lot.

  58. mirekh says:

    Great tutorial! Difficult things like piece of cake. Thanks a lot Mr Patel.

  59. Hi Viral Patel . This tutorial is very very useful for me.I think it also used for every basic Angular JS learners.

    Keep it up.

    We are expect more article like this with some other examples.

  60. Mahesh says:

    Excellent tutorial. Easy to understand the concepts.

  61. vkstream says:

    Hello Viral,
    Thanks for tutorials these are totally awesome for us …!!!!

  62. vkstream says:

    Viral actually I am little bit confused in your example, actually I had tried this code to write in my Eclippse IDE but How and where can I add JavaScript code in my index.html file .FYI I am new in this field so I have a humble request to you please give me the direction regarding this..??

  63. Recan says:

    Hi Viral i like your post you have made following Angular JS, this tutorial is really nice, can you please provide a tutorial session on Simple CURD application using jdbc driver, i followed this session and implemented with REST API , i need to do it with out any APIs with simple query classes, looking forward to hearing from you, many thanks

  64. pravy says:

    Hi viral, nice tutorial. I’m developing angularjs application using java. I have a issue that, how to maintain session after page refresh. could you please help me to find out solution.
    here is the link which i briefed with code snippet.

    http://stackoverflow.com/questions/23132381/when-page-refresh-how-to-call-back-function-in-angularjs

  65. Ron says:

    Excellent Stuff. Nice and simple.

  66. Alex says:

    Thank you very much! excellent tutorials! please keep up the good wok

  67. Bman says:

    Thanks for the article. This is very helpful for a beginner. I got here searching for the nested controllers – the concise examples cleared up a lot of questions.

  68. Krushnapada says:

    How can open new tab when click popup window Ok button using angularjs

  69. Luiz Rogério says:

    Great tutorial! Thanks :)

  70. Sandy says:

    Excellent Tutorial. Easy to understand the concepts due to the indepth explanations with the simple examples. Looking forward for more such tutorials on more advanced features and concepts of AngularJS. Thanks again :)

  71. Manan D Shah says:

    Thanks viral bhai….

    Awesome work…. I am a beginner in angular js… It helps me aloat…

    waiting for more such kind of tutorials on various technologies….

    • Manan D Shah says:

      live demo on jsfiddle…. :) great

  72. Vimal says:

    Great way of start learning AngularJS!!!
    Thanks for the heads up!!

  73. Nitin says:

    Nice Post…..

  74. Gerard says:

    Nice one! By the way, you could skip the for in loop once the contact is updated using

    $scope.contacts[i] = $scope.newcontact; break; 

    in 6.2. Otherwise the for keeps going.

  75. Anudeep says:

    nice tutorial viral.really i learnt so much from this.
    Thank you

  76. Pushkar Kumar says:

    Hi,
    can u plz help me to write the code of sorting data of table when we click on column header….in angularjs.

    Thanks

  77. Puneet Gupta says:

    Good Article

  78. wasim khan says:

    useful article for beginners

  79. ankur says:

    Hi all …but here if we save one contact the row is appended …after that if we click save rows will keep appending ..how can we make save button to work only once

  80. Ankur says:

    but here if we add a record after that we dont give any values and click empty record will keep on inserting …ne way to avoid it ?

  81. Nice tutorial

  82. Great Angular Code.
    Which PHP framework is more perfect with Angular.

  83. Suraj says:

    Good Article it actually made Angular JS simpler……

  84. Armaan says:

    Good Article !!!

  85. Phaneendra says:

    Nice, tutorial. Awesome

  86. Santhosh says:

    Great tutorial ! Nice explanatories
    But I couldn’t make this work ,

    var myApp = angular.module(‘myApp’,[]);

    myApp.controller(‘ContactController’, [‘$scope’, function($scope) {
    $scope.contacts = [“[email protected]”, “[email protected]”];

    $scope.add = function() {
    $scope.contacts.push($scope.contact);
    $scope.contact = “”;
    }
    }]);

    Things you explained in section 3.1 . Any help is highly appreciated

    • amit says:

      santosh try this :
      myApp.controller(‘ContactController’, function($scope) {
      // logic
      });

  87. Your first example (1. What are Scopes?) does not work with latest beta of Angular:

    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular.js"> 
    


    I get Error: [ng:areq] Argument ‘ContactController’ is not a function, got undefined

    But it works fine with yours :

    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    

  88. The AngularJS controller has changed so the examples of bad practise in beginning of blogpost will not work in version 1.3. As Viral Patel writes: “We should define Controller within Modules.” I wrote a blog post about the changes in version 1.3 http://www.lcube.se/angular-js-controller-error-argument-is-not-a-function/ it might help if you get error of the type Argument is not a function.

  89. khushiram Ginnare says:

    Great tutoria for beginner’s thank’s a lot.

  90. Nady says:

    Awesome man keep it up!!!!
    U rock!!!

  91. swaroop says:

    i am not understanding anything..suggest any sites

  92. Sanjay says:

    Really nice tutorial, i love it.. please keep posting…

  93. Amutha says:

    No words to describe!!!! Really helpful!!!!

  94. Anouar Kacem says:

    Hi, nice tutorial but in the last example your code should be like this :

    <tr ng-repeat="contact in contacts" class="ng-scope">
        <td class="ng-binding">{{contact.name}}</td>
        <td class="ng-binding">{{contact.email}}</td>
        <td class="ng-binding">{{contact.phone}}</td>
        <td>
            <a href="#" ng-click="edit(contact.id)">edit</a> | 
            <a href="#" ng-click="delete(contact.id)">delete</a>
        </td>
     </tr>
    

  95. sri says:

    hi, nice tut. can u please give example to display the data in dropdownlist from database …

  96. lino says:

    Very Nice tutorial but i don’t understand this
    ” for (i in $scope.contacts) ”
    how it loop ?
    what is ” i ” ?

    sry for bad english :)

  97. Aftab Naveed says:

    Nice tutorial but I found a small bug in line

    <ul>
            <!-- ngRepeat: contact in contacts --><li ng-repeat=&quot;contact in contacts&quot; class=&quot;ng-scope ng-binding&quot;> [email protected] </li><li ng-repeat=&quot;contact in contacts&quot; class=&quot;ng-scope ng-binding&quot;> [email protected] </li>
        </ul>
    

    {{contact}} is missing between li

  98. Ilaya says:

    Bookmarked your angular js tutorial. Explained very well.

  99. Sajin says:

    easily understanding u r examples

  100. kaouther says:

    svp comment calculer la somme de prix d’une liste de produits

    • Nice One….

      • Ram says:

        This is default description.

  101. Koteeswaran says:

    nice article

  102. Huanle Hu says:

    Very nice tutorial. Thank you for this useful article.

  103. Jacob Ormerod says:

    All such learning assistance is appreciated, but there needs to be more discussion on changes in angular at about version 1.3 (two years ago?). It seems that the ng-app directive must declare a module in order to bind a controller. For instance Then, the following js:
    var app = angular.module(‘myApp’, []);
    app.controller(‘ContactController’, function($scope) {
    // function ContactController($scope) {
    $scope.contacts = [“[email protected]”, “[email protected]”];
    $scope.add = function() {
    $scope.contacts.push($scope.newcontact);
    $scope.newcontact = “”;
    }
    }
    );

  104. Alfetta159 says:

    Perhaps it’s time to update this article as some samples don’t work with more contemporary versions of Angular JS. Thx!

  105. Pankaj says:

    Hi Viral,
    your tutorial is very helpful for me…..I’m new in angularjs…but its great ….
    Thanks a lot

  106. Leo says:

    I wanted to know what is difference when you define a controller like

    sampleApp.controller(‘ShowOrderController’, function($scope, $routeParams) {

    some data here

    });

    and

    myApp.controller(‘ContactController’, [‘$scope’, function($scope) {
    some data here
    ]}

    Why do you not define the $scope in an array in the second example?

    • Leo says:

      Sorry I meant why do you define $scope in an array in the second example?

  107. Akeshwar says:

    Hi, thanks for the article and explaining everything right from the basics. I just wanted to point out that the first example code is not working at the current angularjs version, 1.4.3
    However, it works fine with 1.0.7
    Can you please explain how to make the code compatible on the newer version?

  108. Riley says:

    Great article/tutorial!

    I noticed one issue with section 3.1. A quick search put me on track though.
    3.1 doesn’t mention that:
    “” must be modified to “” so that angular knows that ContactController is in the scope of the myApp module.

    Thanks again!

  109. Arash Masir says:

    It was so nice and useful , thank you so much…

  110. Rohit Tewari says:

    Thank you so much. Could you help us in CRUD example also. I want to know data pulling from database.

  111. Daniel says:

    Gracias por compartir !
    :)

  112. Carol says:

    Thanks! it is a very good and informative article

  113. Carol says:

    Thanks for your article

  114. Thank you for your clear, clean and concise way of explanation. I’ve been reading your tutorial for factory and service as well. Great job. I’ve bookmarked your stuff and will return! Thought you should know.

  115. Satish SM says:

    Fantastic Tuto! Great Buddy! Simple AWESOME and MORE CLEAR

  116. brahma says:

    it’s so useful.. Thank you..

  117. Credo Systemz says:

    Amazing, thanks a lot my friend, I was also siting like a your banner image when I was thrown into Selenium.
    When I started learning then I understood it has got really cool stuff.
    I can vouch webdriver has proved the best feature in Selenium framework.
    thanks a lot for taking a time to share a wonderful article.

  118. piccosoft says:

    Your blog is very nice… Thanks for sharing your information…

  119. Natasha Bieber says:

    Hey Viral! I think the content covered in the article is quiet impressive and brilliantly conveyed. Very nice blog. Appreciate your efforts. Thank you :)

Leave a Reply

Your email address will not be published. Required fields are marked *