Mikyas TADESSE Mikyas TADESSE - 3 years ago 125
HTML Question

Angular code not working with express

Am having a problem with angular. My angular code works fine when i run it alone but doesn't work when i access it on localhost with express. What happens is that it displays the html file alone.
my server code is :

var express = require('express'),
app = express();
app.get('/', function(req, res) {
app.listen(3000, function() {
console.log('I\'m listening...');

my angular controller code is

var app = angular.module('tiks', []);

app.controller('mainController', function($scope){

$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};

$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.newPost = {created_by: '', text: '', created_at: ''};

and the angularised html code is

<!doctype html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/tiks.js"></script>
<body ng-app="tiks">
<div id='main' ng-controller="mainController">
<form ng-Submit="post()">
<input required type="text" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="button" type="submit" value="Chirp!" />
<div id="post-stream">
<h4>Tiks Feed</h4>
<div class='post' ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.created_by}} says {{post.text}} at {{post.created_at}}</p>

please help

Answer Source

Your HTML is asking for javascripts/tiks.js at the script tag, but your server has no route configured to serve it.

Try checking the requests being done, for example using Google Chrome Developer tools network tab, and you will probably see a 404 error when the .js file is requested.

You should use express.static to serve files from folder instead of defining specific resources individually as you are doing for ./app/client/main.html.

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

then you would have to access http://localhost/main.html to access it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download