0

Sorry, I'm a newbie at this

Let's say i have the following in node express

router.get('/:name', function(req, res, next) {
      res.render("test", {test:req.test});
});

how to do I get the angular to pick up the test variable?

i tried doing in the html page

    <div ng-controller='UserCtrl'>{{ data }}</div>
    <script>
         var test=!{JSON.stringify(test)};
    </script>

then on the angular page

productApp.controller('UserCtrl',function UserCtrl($scope){
    $scope.data=test;
});

the req.test looks like this

 [
   { 
      name: 'test' 
   }
 ]

the 'data' shows empty everytime.

thank you for your help

luis
  • 202
  • 5
  • 13

4 Answers4

0

Inside your express res.json() is, in my opinion, the best option you have since any object passed to it will be converted to JSON other way you can do it like you've done but render is more suited to html where you have to render a nice little view for the client or there is some sort of manipulation involved before sending the JSON on the wire or the json is too big and you don't want to make you router file dirty and rather delegate that to a view file.. else res.json() is a very neat way to do it.

Modify your controller code like:

productApp.controller('UserCtrl',['$scope', '$http' , function($scope, $http){
    $http.get('/test').then(
           function(response){
               $scope.data = test;
           },
           function(err){
               console.error(err);
           }); //'/test' <- this is the url; 
    //$scope.data=test;
}]);

and remove this from your code

<script>
    var test=!{JSON.stringify(test)};
</script>
Minato
  • 4,383
  • 1
  • 22
  • 28
0

If you want Angular to talk to a server, the most common way is through an AJAX request. Angular has a whole service to help you with this communication.

https://docs.angularjs.org/api/ng/service/$http

The first example pretty much does exactly what you are looking for:

$http({
  method: 'GET',
  url: '/testName'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

It uses promises for the response. Just add your actions in the proper call back function and away you go.

hbillings
  • 174
  • 1
  • 1
  • 7
  • thanks @hbillings, this works, same as minato's, i tried using this without res.json() on the server.js but i didn't work, only worked when i use the json(), – luis Nov 25 '15 at 17:55
0

You will need to use ajax call from an angular script or service in order to get the express js backend response.

You can create a service like below -

productApp.service("API", function($http){

     this.callAPI = function(name){

         return $http({
            url : "localhost:3000/"+name, 
            data : "", // pass data if any here
            method: "get"
         });
     }; 

});

Then you will need inject this service in your controller and call like below -

productApp.controller('UserCtrl',function UserCtrl($scope, API){
   //$scope.data=test;

   // call service api here 
   API.callAPI("some name").then(function(response){
       $scope.data = response;
     }, function(){ 
        // error goes here 
   });
});

Also, you can change your express js app to send the JSON data as follows -

res.json({...}); // instead of res.render(..);
Chandan
  • 1,128
  • 9
  • 11
  • thanks @chandan I tried this already but it doesn't seem to be working, the "some name" part, i tried putting the parameter name e.g. "luis" but still didn't work, what am i doing wrong there? – luis Nov 25 '15 at 18:17
0

I would recommend doing an $http service call to receive this variable BUT if you truly want this variable/data rendered directly in to the page and available in the controller, you should consider doing the following:

In the rendered/returned HTML:

<head>
...
<script>
    angular.module('myAppConfig', [])
        .value('MyTestConfig', !{JSON.stringify(test)});
</script>
</head>
<body ng-app="myApp">
...        
    <div ng-controller='UserCtrl'>{{ data }}</div>        
...
</body>

This will setup an injectable configuration value called 'MyTestConfig'. Ideally, this should be part of a bigger object or service so you could do things like Config.apiPath or Config.getStaticResource('my-resource.png')

Your controller will now look like this:

productApp.controller('UserCtrl', function UserCtrl($scope, MyTestConfig){
    $scope.data = MyTestConfig;
});

and your original modal definition will look something like this:

angular.module('myApp', ['myAppConfig']);

You may need to shuffle around where the script tag is depending on how you have configured your views. This will also only work before injection has been finalized, aka, this will not work for partials.

Jaymes Bearden
  • 2,009
  • 2
  • 21
  • 24
  • thank you @Jaymes i tried changing everything with this script but it didn't work, it returns a empty data :-( – luis Nov 25 '15 at 18:03
  • Ahh, I forgot to ask, what template language are you using as this will change the .value() section. If you are using EJS as the view renderer, try <%= JSON.stringify(test) %> instead of !{JSON.stringify(test)} – Jaymes Bearden Nov 25 '15 at 20:23