Tutorial: Integrating AngularJS with NodeJS

Integrating AngularJS with NodeJS
Integrating AngularJS with NodeJS

I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it’s a very common to see people asking how to integrate both, so this will be a very simple beginner level tutorial in which I’ll give an example to demonstrate how AngularJS and NodeJS can work together.

I’m assuming you have already set your enviroment, so we are going to start by creating our NodeJS project, to do that I’m going to use express, if you don’t have it yet just install via npm with the following command line:

npm install express-generator -g

With express installed simply navigate via terminal to the folder you want your project to be located and execute the command express passing your project name as a parameter, like this:

express myNodeProject

Now that your project is created, you can open it with the text editor of your choice, I’m going to use Sublime Text for this tutorial. When you do it you’ll see that express has already created the basic project structure for you:

Folder Structure
Folder Structure

By default, express uses Jade as the view engine, as you can see in the views folder we already have some jade files, which we are not going use, you can get rid of them later if you want. We’ll need to make some changes here to be able to use angularjs. Let’s begin by opening the file routes/index.js, it contains the following code:

var express = require('express');
var router = express.Router();
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
module.exports = router;

That’s the code responsible for rendering and redirecting to the index.jade file, what we need to do here is to change it a little bit and make it redirect to our angularjs index.html file (which we are going to create in a moment). After the changes the code should look like this:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

Now we need to create our index.html file, I’m going to put it in the views folder with the jade files. This is how my HTML code looks like:

<!DOCTYPE html>
<html ng-app="angularjsNodejsTutorial">
    <head>
        <title>Integrating AngularJS with NodeJS</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="javascripts/app.js" type="text/javascript"></script> <!-- not created yet -->
    </head>
    <body >
        <div ng-controller="myController">
        </div>
    </body>
</html>

In this file you can use not only AngularJS, but any javascript library you want, if you run your project you’ll see that nodejs is already redirecting to this file, you can now create you angularjs module and start writing some angularjs code as usual.

At this point you are already using angular and node in your application, but they are kind of independent from each other, there are no communication between them. To finish up this tutorial I’m going to show how AngularJS can make a request to NodeJS. But before we do that, we need to come back to the index.js file (the one we just modified) and create a function to return some data, which will be called when we make the request from our angularjs controller, just copy the following code and paste it right above the module.exports on your index.js.

router.get('/data', function(req,res){
	res.json([{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}]);
});

What is happening here is that the router.get function is assigning a function to the url ‘/data’, so when the user types ‘/data’ in the browser, node will call this function, which is doing nothing more than returning a json, it could be getting and handling data from the database, but as I want to keep it simple, a static json will do the job.

Now let’s create our app.js file, as you can see in the HTML code, it’s already referenced there. I’m going to put it on the public/javascript folder.

var app = angular.module('angularjsNodejsTutorial',[]);
app.controller('myController', function($scope, $http) {
    $scope.data = [];
    var request = $http.get('/data');    
    request.success(function(data) {
        $scope.data = data;
    });
    request.error(function(data){
        console.log('Error: ' + data);
    });
});

This is also a very straightforward code, I’m using the function $http.get with the argumentet ‘/data’ to make the request, then I’m assigning the result to $scope.data.

Now we just need to modify a little bit our HTML to make it iterate over our data and show it on the screen, just add this to the div with the ng-controller:

<ul ng-repeat="item in data">
	<li>Name: {{item.name}}, City: {{item.city}}</li>
</ul>

That’s it!! Now just run your project by executing npm start on the terminal and you’ll be able to access the application on your browser by typing localhost:3000, if you did everything right you should see a page with the data from our json.

Hope this tutorial was helpful, till the next one!!

Recommended for you

One comment on “Tutorial: Integrating AngularJS with NodeJS

  1. Swapnil

    Hi Leo,
    Thanks for this wonderful article. Helped a lot. Asking a very basic question as I just started AngularJS and node.js. So, It’s working fine when I did npm start and then localhost:3000/data from the browser. However, when I try to run it via views/index.html file it gives me —
    ” Uncaught Error: [$injector:modulerr] Failed to instantiate module angularjsNodejsTutorial due to:
    Error: [$injector:nomod] Module ‘angularjsNodejsTutorial’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.” exception.
    Is there any way to get this returned json data in the controller back and display it via the html file? I am using webstorm IDE btw. Thanks in advance and kudos to you.

Leave a Reply

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

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>