AngularJS: A Simple Application

We have already discussed much about AngularJS in the previous articles. So in this article we will go a bit further and create a very simple application using AngularJS. The application would be a simple Listing application where we will show the list of my favorite food items. Also we would have the ability to add more items to the list.

Continuing from the previous article, we modify our view like this.



We've added a text box to enter the new item and a button to add that inserted item to the list.

In the controller part, we have the method addNew, that would do the adding of the entered item in the list.



Well, the thing is simple. Let's break the code down to understand it.



The Controller

This is the controller to which we have bound our division of the view to. Now we need a list of items that we will iterate over and display them onto the screen.



So we've created a list listOfThingsILove, in which we have added 3 default items. To enable the user to add any new item to the list, we need to create the click listener of the button and add the entered value to the list.



The property newItem is bound to the view and we are adding the value of that property to the list.

Here is the entire JavaScript code:

  1. var myController = function($scope){  
  2.    
  3.     $scope.listOfThingsILove = [new NewItem("Milk"), new NewItem("Rasmalai"),   
  4.                             new NewItem("Rasgulla")];  
  5.           
  6.     $scope.addNew = function(){  
  7.         $scope.listOfThingsILove.push(new NewItem($scope.newItem));  
  8.         $scope.newItem = "";  
  9.     }  
  10. }  
  11.    
  12. var NewItem = function(name){  
  13.     this.name = name;  

On the View side we have:

  1. <!DOCTYPE html>  
  2. <html ng-app>  
  3. <head>  
  4.     <title>Angular Demo</title>     
  5. </head>  
  6. <body>  
  7.    
  8.     <div>  
  9.    
  10.        <div ng-controller="myController">                 
  11.                <ul ng-repeat="item in listOfThingsILove">      
  12.                    <li>{{item.name}}</li>  
  13.                </ul>                 
  14.    
  15.                <input type="text" ng-model="newItem"/>  
  16.                <input type="button" ng-click="addNew()" value="Add"/>  
  17.        </div>  
  18.    
  19.    </div>  
  20.    
  21.  <script src="js/angular.js"></script>  
  22.  <script src="js/viewmodel.js"></script>  
  23.    
  24. </body>  
  25. </html> 



Running the code we would have the following output in the browser.



I hope you like this article.


Similar Articles