Angular JS: The Controllers

In the previous article, we began our journey with an introduction to the basics of Angular. In this article however, we will continue on that journey by introducing Controllers into the picture.

If you have gone through the previous article about the MVC architecture, you should understand what a controller basically is. If you didn't, I suggest you to have a look at that article before continuing.

So, we begin with a simple regular Angular Skeleton.


With this in place, we can begin with the creation of the controller and writing some JavaScript. To add the controller to the view we do the following.


The controller technology is basically a JavaScript function with the $scope object as parameter. We will be talking about the $scope object more in later articles. Our controller will look something like:



If you look closely, we have defined a collection technologies, in the $scope object, that can be accessed from the View (HTML) directly. Since it's an array we need to loop though in order to display it on the screen.



On running the code, the output will be the following.


Here is the entire HTML:

  1. <!DOCTYPE html>  
  2. <html ng-app>  
  3. <head>  
  4.    <title>Angular Demo</title>  
  5.    <script src="js/angular.js"></script>  
  6.    
  7.    <script src="js/viewmodel.js">  
  8.    </script>  
  9. </head>  
  10. <body ng-controller="Technology">  
  11.    <ul>  
  12.       <li ng-repeat="technology in technologies">  
  13.          {{technology.technologyName}}  
  14.       </li>  
  15.    </ul>  
  16. </body>  
  17. </html> 

Here is the JavaScript code:

  1. function Technology($scope){  
  2.    $scope.technologies =  
  3.    [{technologyName: 'HTML5'},   
  4.    {technologyName:'.Net'},   
  5.    {technologyName:'JAVA'}];  

I hope you like this article. Stay tuned for more.

Up Next
    Ebook Download
    View all
    Learn
    View all