javascript - 以 Angular 访问全局变量

标签 javascript express angularjs

我正在使用 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/

相关文章:

javascript - 变量在一个地方被设置为 Nan,但在另一位置正确设置

javascript - 如何给用coffeebar编译的文件下命令

javascript - 如何将文件夹中的所有文件作为模块导入并将所有文件导出为对象?

javascript - 如何迭代创建记录集合并一次呈现所有记录?

javascript - 跨域情况下 javascript 代码无法访问带有 "Location" header 的 XMLHttpRequest POST 响应

javascript - promise 无法正常工作的 AngularJS 工厂

javascript - 用于检查 CouchDB nodejs nano 中是否存在文档的自定义函数

javascript - 无法弄清楚使用 Firebase 登录 Github

javascript - 如何使用 AngularJS 正确发送包含逗号的 URL 参数?

具有 HTML5 模式的 anchor 标记中的 AngularJS 应用程序链接/路由