如何将 node.js 服务器变量传递到我的 angular/html 视图中? [英] How do I pass node.js server variables into my angular/html view?

查看:19
本文介绍了如何将 node.js 服务器变量传递到我的 angular/html 视图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 app.js 文件中有这个路由来启动服务器

I have this route in my app.js file that starts the server

app.get('/view/:item_id', function(req,res){
    var A = 5;
    res.render('view_item');

我的 view_item.html 中有这个:

and I have this in my view_item.html:

<p>{{A}}</p>

我希望它显示变量值 - 5.如果我使用像 jade 这样的模板引擎,那就很容易了.我可以将服务器代码的第三行更改为 res.render({A:A},'view_item');

I want it to display the variable value - 5. If I were using a template engine such as jade it would be easy. I could change that third line of my server code to res.render({A:A},'view_item');

但我使用 html 作为我的模板引擎.到目前为止,我的研究告诉我,使用带有 angular 的模板引擎通常是一个坏主意,并且总有一种方法可以使用 angular 的内置模板系统来做到这一点.那么我该怎么做呢?我是否以某种方式将它传递给 $scope 并包含像

But I am using html as my template engine. My research so far has told me that using a template engine with angular is usually a bad idea, and there is always a way to do it using angular's built in template system. So how do I do this? Do I somehow pass it to the $scope and include like

<script>
    $scope.A = {{A}};
</script>

我还没有在任何地方看到这样做过,所以我认为这不是可行的方法.

I haven't seen this done anywhere so I don't think its the way to go.

推荐答案

这是一个两步过程.

  1. 首先,您需要在 node 中使用像 express 这样的库(服务器库)来设置正确的路由(REST 服务)来响应您的请求:
  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:

服务器端

//app = express();
    app.get('/api/:paramID1/:paramID2',function(req, res){
        return res.json({ A: 5 });
    });

  1. 客户端,您需要一个ajax调用来调用服务,例如:

  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 );
});

请注意,在使用 REST 时,可以根据您的需要调用不同类型的方法",例如 POST、DELETE、UPDATE 或刚刚在示例 GET 中提到的方法.

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.

这篇关于如何将 node.js 服务器变量传递到我的 angular/html 视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆