Building your first AngularJS app – Shopping list

In this post, I will explain about creating a simple shopping list reminder tool using AngularJS.

Click to view Demo

angular-shopping-list-demo

You can download the source code, from Github https://github.com/naga90/learnings/tree/angular-learnings/shopping-list


githubLink

Operations
In this tool,

  • We are going to add items to the shopping list
  • We can delete it if we don’t need that item
  • We can strike that item if it is purchased
  • We can undo the strike if done mistakenly

Explanation
In this project, we are going to use angularJS version 1.5.7 from cloudfare. We can use CDN version. Once we include AngularJS javaScript file we are ready to code with AngularJS.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>

First create a html document, with the following code.

<!DOCTYPE html>
<head>
	<title>Shopping List tool - Angular Demo</title>
</head>
<body>

<div ng-app="myFirstApp">
	<div ng-controller="firstController" class="content">
	
	</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>

In this code, we have used ng-app=”myFirstApp” which denotes the angular app named “myFirstApp”, followed by ng-controller=”firstController” which denotes the firstController.

Then in js/main.js add the following code.

var myFirstApp = angular.module('myFirstApp',[]);
myFirstApp.controller('firstController',function($scope){

});

Here we are writing angularJS code for the ng-app and ng-controller we created earlier in HTML file.

$scope is the variables which binds data between controller and html view.

Next, in main.js add the following lines inside controller.

$scope.todo_lists = ['Fruits','Vegetables','Milk','Coffee','Water bottle','White Board','Black Marker'];

We are creating an angular array with default shopping items, that gets loaded when user opens our page.

And in HTML file, add the following code inside ng-controller=”firstController”

<ol>
	<li ng-repeat="item in todo_lists"> 
		<span class="item"> {{ item  }} </span> &nbsp; 
	</li>
</ol>

This will display all the default items in list, as ordered list in HTML. ng-repeat will repeat through each item in array and displays the item. It is similar to loop in programming languages.

Now, we can add items to the list. Add a text box to html and when user enters some value and press add button, add the item to list. Lets see how we do it.

Add the following code to HTML file after ng-controller.

<div class="form-group">
	<h2>Your Shopping List</h2>
	<input type="text" ng-model="new_item" placeholder="Add Item" ng-class='{danger: form_error}'>
	<button ng-click="addItem()">Add Item</button>
</div> 

When user clicks on Add Item button, ng-model value is fetched in addItem() function, if value is empty, danger class is added to input box which makes the border colour red for input box and no operation is performed. If value is not empty, value is added to scope array and it automatically gets added to the list in HTML page. We don’t have to add code to append data to list. Two way data binding works that way. It makes our work easier.

Add this code to your main.js file in controllers to add item to list.

$scope.addItem = function () {
	if($scope.new_item.length == 0){
		$scope.form_error = true;
	}
	else{
		$scope.form_error = false;
		$scope.todo_lists.unshift($scope.new_item);	
		$scope.new_item = '';
	}
}

unshift adds item to the beginning of array, where as push adds item to the end of array. You can use push if you want add item to end of list. After adding item, empty $scope.new_item, so user can add next item.

Now we can see, how to delete an item.

$scope.deleteItem = function(i){
	if(confirm("Are  you sure?")){
		$scope.todo_lists.splice(i, 1);
	}
}

On clicking delete icon, we pass index of the array and we remove element from array using that index. we use splice to remove element. It automatically removes element from list in html page.

Now we can see about strike item. Add this code to your html inside li in ng-repeat.

<span class="item" ng-class="{striken : item_striken$index}"> {{ item }} </span> 
<div class="right">
	<i class="fa fa-check" ng-show="!item_striken$index" ng-click="item_striken$index = !item_striken$index"></i> 
	<i class="fa fa-times" ng-show="item_striken$index" ng-click="item_striken$index = !item_striken$index"></i> &nbsp;
	<i class="fa fa-trash" ng-click="deleteItem($index)"></i>
</div> 

This might look complex for the beginners. I will explain what has been done here.

item_striken$index denotes each item in the list. Index refers to array index. This is the index that we passed to delete function earlier.

ng-show shows or hides the element based on condition. item_striken$index value changes on click. Based on true or false, tick or cross is displayed.

in span, ng-class=”{striken : item_striken$index}” this will add class striken to span, if item_striken$index is true.

Finally we can add a filter. Search box for filtering the list.

For this we add a text box that gets search keyword from user.

<label>Search: <input ng-model="searchText"></label>

And we slightly modify ng-repeat.

<li ng-repeat="item in todo_lists | filter:searchText">

Hint : In ng-repeat, we will get angular error if we have duplicate values. For example, if user enters Pen twice, our app crashes. So we slightly modify our ng-repeat, to be tracked by $index instead of item.

Finally ng-repeat looks like

<li ng-repeat="item in todo_lists | filter:searchText track by $index "> 

Our Final, HTML code looks like

<!DOCTYPE html>
<head>
	<title>Shopping List tool - Angular Demo</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div ng-app="myFirstApp">
	<div ng-controller="firstController" class="content">
		<div class="form-group">
			<h2>Your Shopping List</h2>
			<input type="text" ng-model="new_item" placeholder="Add Item" ng-class='{danger: form_error}'>
			<button ng-click="addItem()">Add Item</button>
		</div>
		<br><br>
		<div style="background-color:#FFFBA2;padding:10px;">
			<div style="text-align:center;background-color:none;">
				<label>Search: <input ng-model="searchText"></label>
			</div>
			<hr>
			<ol>
				<li ng-repeat="item in todo_lists | filter:searchText track by $index "> 
					<span class="item" ng-class="{striken : item_striken$index}"> {{ item | capitalize }} </span> &nbsp; 
					<div class="right">
						<i class="fa fa-check" ng-show="!item_striken$index" ng-click="item_striken$index = !item_striken$index"></i> 
						<i class="fa fa-times" ng-show="item_striken$index" ng-click="item_striken$index = !item_striken$index"></i> &nbsp;
						<i class="fa fa-trash" ng-click="deleteItem($index)"></i>
					</div> 
				</li>
			</ol>
		</div>	
	</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="js/main.js"></script>

</body>
</html>

And our Angular main.js file looks like

var myFirstApp = angular.module('myFirstApp',[]);
myFirstApp.controller('firstController',function($scope){
	$scope.todo_lists = ['Fruits','Vegetables','Milk','Coffee','Water bottle','White Board','Black Marker'];
	$scope.new_item = ""; $scope.form_error = "";
	
	$scope.addItem = function () {
		if($scope.new_item.length == 0){
			$scope.form_error = true;
		}
		else{
			$scope.form_error = false;
			$scope.todo_lists.unshift($scope.new_item);	
			$scope.new_item = '';
		}
    }

    $scope.deleteItem = function(i){
    	if(confirm("Are  you sure?")){
    		$scope.todo_lists.splice(i, 1);
    	}
    }
});

myFirstApp.filter('capitalize', function() {
    return function(input) {
      return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : '';
    }
});

Thanks for reading.

You can download the source code, from github https://github.com/naga90/learnings/tree/angular-learnings/shopping-list


githubLink

Nagarajan
Follow me

Nagarajan

Web Developer at Energy Alternatives India
I'm interested in developing Web applications andkeen on learning new technologies.

View Nagarajan's Profile
Nagarajan
Follow me

Latest posts by Nagarajan (see all)

Leave a Reply

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