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:
- var myController = function($scope){
-
- $scope.listOfThingsILove = [new NewItem("Milk"), new NewItem("Rasmalai"),
- new NewItem("Rasgulla")];
-
- $scope.addNew = function(){
- $scope.listOfThingsILove.push(new NewItem($scope.newItem));
- $scope.newItem = "";
- }
- }
-
- var NewItem = function(name){
- this.name = name;
- }
On the View side we have:
- <!DOCTYPE html>
- <html ng-app>
- <head>
- <title>Angular Demo</title>
- </head>
- <body>
-
- <div>
-
- <div ng-controller="myController">
- <ul ng-repeat="item in listOfThingsILove">
- <li>{{item.name}}</li>
- </ul>
-
- <input type="text" ng-model="newItem"/>
- <input type="button" ng-click="addNew()" value="Add"/>
- </div>
-
- </div>
-
- <script src="js/angular.js"></script>
- <script src="js/viewmodel.js"></script>
-
- </body>
- </html>
Running the code we would have the following output in the browser.
I hope you like this article.