How do I pass node.js server variables into my angular/html view?

倾然丶 夕夏残阳落幕 提交于 2019-11-28 08:31:15
Dalorzo

This is a two step process.

  1. First, you need to use a library(server library) like express in node to set the proper routings (REST Services) to respond to your Requests:

Server Side

//app = express();
    app.get('/api/:paramID1/:paramID2',function(req, res){
        return res.json({ A: 5 });
    });
  1. On the client side, you need an ajax call to invoke the service like:

    $http.get( "/api/1/abc").success(function( data ) {
      $scope.A= data; //from your sample;
      alert( "Load was performed. " + data );
    });
    

Please note that when using REST there are different type of "methods" that can be invoked depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.

If you are using Angular you should probably be building a single page app -- this would apply for most of the modern front end frameworks. For SPAs you start out with a basic html file (probably index.html). Then, your framework handles the rendering of everything else. Your server may also emit templates, but it will never render anything itself.

app.get('/view/:item_id', function(req,res){

This shouldn't be rendering anything or returning HTML. Instead, you should be returning data that the front end will use to render -- preferably as JSON.

res.json({A: 5});

Then with Angular you would do something like

$http.get("/view/1").success(function (data) {
    ctrl.A = data.A;
});

Your html/template would have something like

<div ng-controller="ctrl as ctrl">
    <div>{{ctrl.A}}</div>

Once $http.get completes, ctrl.A is populated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!