Shubham Tripathi
Shubham Tripathi

Reputation: 85

Working with node js and angular js

I am just trying out node js and angular js. here is my node code:

var http = require('http');
var fs = require('fs');
var sys = require('sys');

http.createServer(function(req, res){
fs.readFile('angularjsex.html',function (err, data){
    res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
    res.write(data);
    res.end();
});
}).listen(8000);

The angularjsex.html file:

    <html ng-app>
    <head>
    <script type="text/javascript" src="angular.js"></script>
    </head>
    <body>
    <div>
    <label>Name:</label>
    <input type="text" ng-model="yourName" placeholder="Enter a name here">
    <hr>
    <h1>Hello {{yourName}}!</h1>
    </div>
    </body>
    </html>

The angular js just does not work. Am i missing something?

Upvotes: 1

Views: 1169

Answers (1)

robertklep
robertklep

Reputation: 203231

You are returning the contents of the file angularjsex.html for every request. In your HTML file, there's a reference to angular.js that the browser will try to load from your server, and that request will get the same (HTML!) contents.

For a solution that works with your current server app, replace this:

<script type="text/javascript" src="angular.js"></script>

With this:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

But I would suggest to start using Express, in which case you can leave the HTML code as is if you change your server to this:

var express = require('express');
var app     = express();

app.use(express.static(__dirname + '/public'));

app.listen(8000);

Create a directory public and place your angularjsex.html and angular.js files into it. To view the result, open http://localhost:8000/angularjsex.html in your browser.

To install Express:

npm install express

Upvotes: 4

Related Questions