Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...