rodrigosanabria rodrigosanabria - 1 year ago 131
AngularJS Question

AngularJS unwanted Behavior when reloading page

I'm developing an Angular application with the MEAN stack, so suppose you got an express route that make a query to the databse, the results are sent in the response:

app.get('/api', function(req, res){
Todo.find({}, "", function(err,todos){
if (err)



In the client-side:

Controller :

Todo.get().success(function(data){ //i got the service with the $http call
$scope.todos = data;

When I go to localhost:8080/#/api, I can see my partial and the data I requested.

The problem that I'm having is that if I omit the hashtag, i don't see the partial, I only see the response data in JSON format.

I also tried to use html5 mode, but if I reload I got the same behavior.

Any ideas on how can I avoid this behavior??

Answer Source

Anything after the # isn't sent to the server. So when you go to localhost:8080/#/api, expressjs just sees a request to / and returns the AngularJS template. AngularJS then routes the browser page using the /#/api, which called the Todo.get() and (I assume) makes a call to localhost:8080/api, returning the data from the DB.

That's why you only get the data when you omit the hash and when you use html5 mode.

I would suggest changing your API call to: /api/todos - return data from the db

And change your AngularJS route to just use: /todos - show the partial and data requested

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