我如何通过的node.js服务器变量到我的角/ HTML视图? [英] How do I pass node.js server variables into my angular/html view?

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

问题描述

我在app.js文件这条路启动服务器

  app.get('/查看/:ITEM_ID',函数(REQ,RES){
    VAR A = 5;
    res.render('view_item');

和我有这个在我的view_item.html:

 < P> {{A}}< / P>

我希望它显示该变量的值 - 如果我使用一个模板引擎如翡翠它会很容易5。我可以在我的服务器code的是第三行改为 res.render({A:A},view_item');

不过,我使用的HTML作为我的模板引擎。我的研究,到目前为止已经告诉我,使用模板引擎的角度通常是一个坏主意,总会有办法采用了棱角分明的内置模板系统来做到这一点。所以我怎么做呢?难道我莫名其妙地把它传递给$范围,包括像

 <脚本>
    $ scope.A = {{A}};
< / SCRIPT>

我还没有看到这个,所以我不认为它要走的路在任何地方进行。


解决方案

这是一个两步的过程。


  1. 首先,你需要使用一个库(服务器库),例如前preSS 节点可设置适当的路线(REST服务),以响应您的请求

服务器端

  //应用=前preSS();
    app.get('/ API /:paramID1 /:paramID2',函数(REQ,RES){
        返回res.json({A:5});
    });

<醇开始=2>

  • 客户端您需要调用Ajax调用服务,如:

      $ http.get(/ API / 1 / ABC)。成功(功能(数据){
      $ scope.A =数据; //从样本;
      警报(进行加载。+数据);
    });


  • 请注意,使用静止时也有不同类型的办法,可以根据您的需求,如POST调用,DELETE,UPDATE或只是在这个例子中提到的一送。

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

    and I have this in my view_item.html:

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

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

    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.

    解决方案

    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 invoke depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.

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

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