[英]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.js文件中有这条路线
app.get('/view/:item_id', function(req,res){
var A = 5;
res.render('view_item');
and I have this in my view_item.html: 我在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. 我希望它显示变量值 - 5.如果我使用的是模板引擎,如jade,那将很容易。 I could change that third line of my server code to
res.render({A:A},'view_item');
我可以将服务器代码的第三行更改为
res.render({A:A},'view_item');
But I am using html as my template engine. 但我使用html作为我的模板引擎。 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.
到目前为止,我的研究告诉我,使用带有角度的模板引擎通常是一个坏主意,并且始终有一种方法可以使用angular的内置模板系统来完成它。 So how do I do this?
那我该怎么做? Do I somehow pass it to the $scope and include like
我以某种方式将它传递给$ scope并包含类似
<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. 这是一个两步过程。
Server Side 服务器端
//app = express();
app.get('/api/:paramID1/:paramID2',function(req, res){
return res.json({ A: 5 });
});
On the client side , you need an ajax call to invoke the service like: 在客户端 ,您需要ajax调用来调用服务,如:
$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. 请注意,使用REST时,可以根据需要调用不同类型的“方法”,例如POST,DELETE,UPDATE或示例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. 如果你使用的是Angular,你可能应该构建一个单页面应用程序 - 这适用于大多数现代前端框架。 For SPAs you start out with a basic html file (probably
index.html
). 对于SPA,您可以从基本的html文件(可能是
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. 这不应该呈现任何内容或返回HTML。 Instead, you should be returning data that the front end will use to render -- preferably as JSON.
相反,您应该返回前端将用于呈现的数据 - 最好是JSON。
res.json({A: 5});
Then with Angular you would do something like 然后使用Angular你会做类似的事情
$http.get("/view/1").success(function (data) {
ctrl.A = data.A;
});
Your html/template would have something like 你的html /模板会有类似的东西
<div ng-controller="ctrl as ctrl">
<div>{{ctrl.A}}</div>
Once $http.get
completes, ctrl.A
is populated. $http.get
完成后,将填充ctrl.A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.