Introduction
AngularJS is best suited for Single Page Application (SPAs) and this tool suits the purpose of using AngularJS in its best. We are going to develop a custom notepad directive using Angular’s directive.
Note - This article assumes the reader to have some experience in developing application using AngularJS. We are going to develop the Note making app using Angular’s factory and directive.
Here’s the use case of our Note Making App.
“A user should be able to create, edit and delete notes. Persisting notes should be handled too so the tool can fetch all the existing notes and show the same to user”.
In order to handle the persistence, we are going to make use of browser’s local storage. Which is one of the key HTML5 feature. One may ask a question, why the need for AngularJS? How about using a simple JavaScript or Jquery? You are absolutely free to develop using any libraries or framework of your choice. But I would like to also mention the reason why I am going with AngularJS. Like I said in the beginning of the article, the Note Making App is a Single-Page Application and Angular is the best framework for develop such applications. Other than that, I was looking for an interesting real world application that can be developed to learn the AngularJS features like directives, factory. I think it’s really important for a beginner to understand the usage of these features with a real world example through which she/he can get a better understanding and the real usage of AngularJS.
Before diving into the Note Making app implementation, here’s something I would like to share with you. This application is developed or extended based on the existing open source app -https://github.com/jsprodotcom/source/blob/master/AngularJS_Note_Taker-source_code.zip
Let us take a look into the snapshot of the Note Making App. Below, you see the note making app running on a browser (Chrome in my case). It is showing two notes for now with a short title of 50 characters. On click of each of the note, you can read full notes and edit the same. There’s a delete button on the right side of each note, you can hit ‘Delete’ button remove the one which you think is no longer needed.In this article, I will be walking you through how to build a simple and elegant note making app developed using AngularJS framework.
AngularJS is best suited for Single Page Application (SPAs) and this tool suits the purpose of using AngularJS in its best. We are going to develop a custom notepad directive using Angular’s directive. Note - This article assumes the reader to have some experience in developing application using AngularJS. We are going to develop the Note making app using Angular’s factory and directive.
Here’s the use case of our Note Making App.
“A user should be able to create, edit and delete notes. Persisting notes should be handled too so the tool can fetch all the existing notes and show the same to user”.
In order to handle the persistence, we are going to make use of browser’s local storage. Which is one of the key HTML5 feature. One may ask a question, why the need for AngularJS? How about using a simple JavaScript or Jquery? You are absolutely free to develop using any libraries or framework of your choice. But I would like to also mention the reason why I am going with AngularJS. Like I said in the beginning of the article, the Note Making App is a Single-Page Application and Angular is the best framework for develop such applications. Other than that, I was looking for an interesting real world application that can be developed to learn the AngularJS features like directives, factory. I think it’s really important for a beginner to understand the usage of these features with a real world example through which she/he can get a better understanding and the real usage of AngularJS.
Before diving into the Note Making app implementation, here’s something I would like to share with you. This application is developed or extended based on the existing open source app -
Let us take a look into the snapshot of the Note Making App. Below, you see the note making app running on a browser (Chrome in my case). It is showing two notes for now with a short title of 50 characters. On click of each of the note, you can read full notes and edit the same. There’s a delete button on the right side of each note, you can hit ‘Delete’ button remove the one which you think is no longer needed.
Using the code
Let us now try to understand the inner working of Notes Making App. Below is the code snippet of the index.html, where you can see the script references for Jquery and Angular. You will also notice the usage of <notepad/> which we call as directive in Angular’s world.
<!DOCTYPE html> <html ng-app="noteApp"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script> document.write('<base href="' + document.location + '" />'); </script> <link rel="stylesheet" href="style.css" /> <script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"> </script> <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script> <script src="app.js"></script> </head> <body> <h1 class="title">The Note Making App</h1> <notepad/> </body> </html>
Now let us take a look into the behind of the scene of the application. As I said before, we are going to develop a custom directive and create an AngularJS based factory.
Below is the code snippet of ‘
notesFactory
’ which will be used within the directive that we will be coding next.
Notice the usage of
localStorage
for managing the user notes. Here’s the snapshot of the local storage items in Google Chrome. We are defining a unique key with the key name as “note” followed by note id which is getting started and incremented by 1.
A note item is saved in
localStorage
by making a call to setItem method and passing in the key asnote<uniqueId>
and value as note text entered by the user. The notes are retrieved by making a call to localStorage’s method ‘getItem’ by passing in the keyname.
The “
getAll
” function returns the list of notes by looping through all the localStorage items. Each of the note item contains a JSON info, one can get the note id, title and content and display the same on UI.
The “
getLastNote
” function returns the last note info present in the localStorage. By looking at the below code, you may think, why not to return the last note by simply getting the note by localStorage item length. The reason being, say if the user deletes one of the note, there will be a mismatch in the note id vs the localStorage items length and we cannot simply be able to grab the last note item from the localStorage. Note - The code can be definitely improved. For now, let us loop through all items.
The “
deleteById
” function is used to delete the existing note item in a localStorage. Loop through each of the local storage items and match the localStorage key name, when there’s a match, just remove that item. app.factory('notesFactory', function() { return { put: function(note) { localStorage.setItem('note' + note.id, JSON.stringify(note)); return this.getAll(); }, get: function(index) { return JSON.parse(localStorage.getItem('note' + index)); }, getLastNote: function(){ var lastNote = []; for (var i = 0; i < localStorage.length; i++) { if (localStorage.key(i).indexOf('note') !== -1) { var note = localStorage.getItem(localStorage.key(i)); lastNote = JSON.parse(note); } } return lastNote; }, getAll: function() { var notes = []; for (var i = 0; i < localStorage.length; i++) { if (localStorage.key(i).indexOf('note') !== -1) { var note = localStorage.getItem(localStorage.key(i)); notes.push(JSON.parse(note)); } } return notes; }, deleteById: function(index){ for (var i = 0; i < localStorage.length; i++) { if(localStorage.key(i) == 'note'+index) { localStorage.removeItem(localStorage.key(i)); break; } } return this.getAll(); } }; });
Now let us create an Angular module and build a “
notepad
” directive. Below is the code snippet for the same. Fist, let us create an Angular module and then create start building the directive. Notice below the directive restrict is set with ‘AE’ means the directive can be an element or attribute.
Here’s how you can use the directive as attribute.
<div notepad></div>
If you are interested in using the below directive as an element. You can follow the below syntax.
<notepad/> or <notepad></notepad>
The key thing about the directive is scope variables and methods part of the link function. Let us take a step back and thing about the functionality. Our application should handle opening or editor and accept notes, save and edit the existing notes. Also the user should be able to delete the same. So we go ahead and create respective methods based on the supporting functionalities.
Here is what we do within the “
openEditor
” function- Set the
editMode
to true. Later you will see it’s usage in the HTML view. - The index will be passed in while we are editing the note or it will be undefined. Which means, it’s a new note. If we have a value, get and set the notetext and scope index.
- Else you can set the notetext as undefined.
The saving of note text is done as below by making a call to “save” method.
- Check whether we have a note text
- Based on the note text, set the note title with a 50 chars limit.
- Set the note content, nothing but the note text.
- If the index is undefined, which means we are creating a new note text. If so, get the last note and set the note id by incrementing the last note id by one.
- Else if you the user is editing an existing note, set the note id with the index.
- Make a call to noteFactory put method by passing in the note.
- Finally make a call to restore method, so it resets the notetext, editMode and index.
The note deletion is performed by making a call to “
delete
” scope method. Here’s what we do.- Alter the user with a confirm message about the note being deleted.
If the user clicks “OK” button, make a call to
deleteById
method of noteFactory by passing in the index to delete.var app = angular.module('noteApp', []); app.directive('notepad', function(notesFactory) { return { restrict: 'AE', scope: {}, link: function(scope, elem, attrs) { scope.openEditor = function(index){ scope.editMode = true; if (index !== undefined) { scope.noteText = notesFactory.get(index).content; scope.index = index; } else scope.noteText = undefined; }; scope.save = function() { if (scope.noteText !== "" && scope.noteText !== undefined) { var note = {}; note.title = scope.noteText.length > 50 ? scope.noteText.substring(0, 50) + '. . .' : scope.noteText; note.content = scope.noteText; if(scope.index == undefined) { if(localStorage.length > 0) { var existingNote = notesFactory.getLastNote(); note.id = existingNote.id + 1; } else{ note.id = 1; } } else{ note.id = scope.index; } scope.notes = notesFactory.put(note); } scope.restore(); }; scope.delete = function(index){ var status = confirm('Do you want to Delete?'); if(status) scope.notes = notesFactory.deleteById(index); } scope.restore = function() { scope.editMode = false; scope.index = undefined; scope.noteText = ""; }; var editor = elem.find('#editor'); scope.restore(); scope.notes = notesFactory.getAll(); editor.bind('keyup keydown', function() { scope.noteText = editor.text().trim(); }); }, templateUrl: 'templateurl.html' }; });
Here is the snapshot of the Note Making app edit note text. Click on the existing note to edit and then modify the text and save the same.
There is one another important thing to discuss. That is about the directive templateUrl. We are setting the directive templateUrl to display the view based on the HTML that we are making use of i.e templateurl.html. Here’s the code snippet for the same.
You can see below, on how the scope methods are being called for adding, saving and deleting a note text. The
editMode
value hides or shows certain things on the view.
Code
<div class="note-area" ng-show="!editMode"> <table> <tr ng-repeat="note in notes|orderBy:'id'"> <td width="100%"> <a href="#" ng-click="openEditor(note.id)" class='notetext'>{{note.title}}</a> <br/> </td> <td> <button ng-click="delete(note.id)" class='deletebutton'>Delete</button> </td> </tr> </table> </div> <div id="editor" ng-show="editMode" class="note-area" contenteditable="true" ng-bind="noteText"></div> <span> <a href="#" ng-click="save()" ng-show="editMode">Save</a> </span> <span> <a href="#" ng-click="openEditor()" ng-show="!editMode">Add Note</a> </span>
Running the Application
Let us now see how we can run the application using NodeJS based module http-server. Please make sure to install NodeJS if you don’t have one - https://nodejs.org/en/download/
Run the below one command prompt to install the http-server globally.
npm install http-server –g
After installing the http-server, you can simply run the application by specifying the following command: http-server <path of the application to run>.
No comments:
Post a Comment