我正在使用 node express 和 angular。在我的 express app.js 中,我声明了一个路由并将一个变量传递给呈现的页面,就像这样......
app.get('/test' function(req, res){
res.render('test', { user: 12345 });
});
在我的“测试” View 中,我使用 ng-controller 将容器链接到 Angular ,就像这样......
<div ng-controller='testCtrl'> <!--some markup here--> </div>
在我的 angular controllers.js 中,我为我的 View 声明了一个函数,就像这样......
function testCtrl($scope) {
/*...some code here...*/
}
如何在我的 Controller 函数中访问我从 express 传递到 View 的“用户”变量?
最佳答案
因为您正在使用模板来呈现 View ,所以有两种不同的执行方式:(1) 您的服务器正在呈现页面(使用 user
var)然后 (2) 浏览器运行 AngularJS。所以您不能将变量从 (1) 传递到 (2)。
但是,有一个指令叫做ngInit
。将在引导期间解析表达式。如果你在 ExpressJS 中使用 Jade 模板,你可以这样做:
div(ng-init='user = "'+user+'"')
这会像这样呈现 HTML:
<div ng-init="user = 'whatever-server-sent'"></div>
因此,当 AngularJS 引导页面的这一部分(或此部分或模板)时,user
将成为一个范围变量,其值来自服务器。
我没有测试 Jade 代码,也不是 Jade 专家,但这应该能让您走上正轨。如果您使用不同的模板引擎,请告诉我,我会修改答案。
关于javascript - 以 Angular 访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15162508/