javascript - 在 Angular 函数中访问 Get 变量

标签 javascript node.js express angularjs

我正在用 node express 和 angular js 构建一个应用程序。我将一个变量传递给我的 View ,如下所示...

app.get('/profile', ensureAuthenticated, function(req, res){
  res.render('profile', { user: req.user });
});

我可以像这样访问我 View 中的变量 (jade)...

h1 #{user}

但是我怎样才能从 Controller 或指令中的 Angular 函数访问这个变量呢?

最佳答案

我写了一篇关于这个主题的博文 - How to pass JavaScript Variables from a server to Angular .

总而言之,您有三个选择:

  1. 使用内嵌 JavaScript 标签(不推荐)
  2. 发出 HTTP 请求(如您在自己的解决方案中所示)
  3. 使用ngInit

您可以阅读我的帖子中的详细信息,我只会展示最后一个,也是我认为最聪明的解决方案。

要将 user 对象从 express 服务器传递到 Angular Controller ,请使用 ngInit 指令:

div(ng-controller="UserCtrl", ng-init="user= #{JSON.stringify(user)}")

这会将内容加载到 Angular 作用域中,您应该能够通过调用 $scope.user 在 Controller 中访问它。

function UserCtrl($scope) {
  console.log($scope.user);
}

关于javascript - 在 Angular 函数中访问 Get 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15009664/

相关文章:

javascript - 组件接收的不是当前值,而是先前的输入值

javascript - Node + Express 开发流程

node.js - 如何在Win CE ARM嵌入式设备上运行node js服务器?

node.js - ExpressJS REST API - 仅供内部使用的端点的最佳实践

javascript - 安全地处理 Node 中的错误 JSON.parse()

javascript - jQuery 克隆列表项在使用each() 函数时都获得相同的文本值

javascript - 通过 Ajax 发送带有额外参数的表单数据?

node.js - npm install 命令作为 root 用户工作正常,但如果命令作为 jenkins 用户执行则抛出错误

node.js - Nodejs promise 类型错误 : Cannot read property 'then' of undefined

javascript - 是否可以将 node.js View 输出缓存为 html 文件?