We have already discussed a lot about angular js in the previous posts. So in this blog post we will go a bit further and create a very simple application using Angular js. The application would be a simple Listing application where we will show the list of my favorite food items. Also we would have the facility to add more items to the list.
On continuing from previous post, 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.
At 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 bind our division of the view to. Now we need a list of items over which we would iterate and display them onto the screen.
So we’ve created a list listOfThingsILove, in which we have added 3 default items. To enable user to add any new item to the list. We have to create the click listener of the button and add the entered value to the list.
newItem is the property bind 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;
14: }
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.
Hope you would like the post.
0 comments