0

I'm changing my node.js application, i was using EJS template engine and now i want use angular.

For this i already install angular and is working good, but now i want get my data, and for this i'm using the $http service:

(function($) {
  app.controller('EventCtrl', ['$scope', '$http', function($scope, $http){
    $scope.data;

    $http.get('/data').
      success(function(data, status, headers, config) {
        $scope.data = data;

      }).
      error(function(data, status, headers, config) {
        $scope.data = data;

      });

  }]);

}(jQuery));

And i'm sending the data in the backend:

  restAPI.GET(options).then(function (result) {
    res.render('data/index.html', {
      event: result,
    });
  }).then(undefined, function (error) {
    console.log(error);
  });

But its returning the HTML from the same page that i'm using the controller. What am i doing wrong here??

What is returning:

<!DOCTYPE html> <html ng-app="app"> <head> <title> Testando Angular </title> </head> <body> <div ng-controller="EventCtrl"> {{data}} </div> </body> <script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="/lib/angular/angular.min.js"></script> <script type="text/javascript" src="/app.js"></script> <script type="text/javascript" src="/controllers/EventCtrl.js"></script> </html>
4
  • Your telling node to send a file. Aren't you wanting to send data? Commented Apr 18, 2015 at 12:33
  • but how can i load the HTML and still send the data?? Commented Apr 18, 2015 at 12:37
  • You'll have to describe specifically what you are trying to accomplish. Commented Apr 18, 2015 at 12:40
  • Node should serve up the html file angular runs on. Then you have to create an API that sends angular whatever data it needs. Commented Apr 18, 2015 at 12:40

1 Answer 1

1

You need to have node serve up the page which angular lives on. (This is using just an example using express) Something like this:

app.get('/', function(req, res) {
    res.sendFile('../public/index.html');
    res.end();
});

Then you need to set up routes for angular to query so it can get data:

app.get('/api/data', function (req, res) {
        //Get some data here however you do that
    res.json(data) //Send your data back to angular in the callback of your database query ( or whatever you are doing )
    }

You use res.render() to send a page. You don't want to send a page. You just want to send data if you are using the $http.get request shown above. Fetch your data and send it with res.json(data)

If you need some insight into how all the pieces fit together, I would recommend working through the following tutorial: Setting Up a MEAN Stack SPA

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.