Click here to Skip to main content
15,886,049 members
Articles / Web Development / HTML
Article

AngularJS based Note Making App in 100 lines (Core Functionality)

Rate me:
Please Sign up or sign in to vote.
4.09/5 (6 votes)
3 Jan 2016CPOL9 min read 17.1K   230   12   1
An AngularJS based Note Making App for Beginners.

Introduction

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 - 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 -

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.

Image 1

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 as note<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. 

Image 2

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

  1. Set the editMode to true. Later you will see it’s usage in the HTML view.
  2. 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.
  3. Else you can set the notetext as undefined.

The saving of note text is done as below by making a call to “save” method.

  1. Check whether we have a note text
  2. Based on the note text, set the note title with a 50 chars limit.
  3. Set the note content, nothing but the note text.
  4. 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.
  5. Else if you the user is editing an existing note, set the note id with the index.
  6. Make a call to noteFactory put method by passing in the note.
  7. 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.

  1. 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. 

Image 3

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.

<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>. 

Image 4

Open up your favorite browser and then navigate to http://localhost:8080/index.html

Points of Interest

It's a nice learning experience in developing application using AngularJS framework. 

History

Version 1.0 - Initial publication - 01/03/2016

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Profile

Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

In Brief

Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.

Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF

Software Development

Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI

Healthcare Domain Experience

CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability

Education

B.E (Computer Science)

CodeProject Contest So Far:

1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro

2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics

3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin

4. Intel App Innovation Contest 2013 - eHealthCare

5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014

6. Grand Prize Winner of CodeProject Android Article Contest 2014

7. Grand Prize Winner of IOT on Azure Contest 2015

Comments and Discussions

 
GeneralMy vote of 4 Pin
Santhakumar M3-Jan-16 7:16
professionalSanthakumar M3-Jan-16 7:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.