如何从控制器中获取index.js中定义的变量?

时间:2014-07-21 13:12:33

标签: javascript angularjs express kraken.js

我正在测试forms-angular(http://www.forms-angular.org/)。

我在DataFormHandler文件中定义了一个index.js变量。而且我需要在我的控制器中获取此变量。我怎么能得到它?此setter不起作用app.set("formHandler", DataFormHandler)

以下是代码:

index.js

'use strict';

var formsAngular = require('forms-angular');  // require formsAngular

var kraken      = require('kraken-js'),
        app     = require('express')(),
        options = {
            onconfig: function (config, next) {
                //any config setup/overrides here
                next(null, config);
            }
        },
        port    = process.env.PORT || 8000;


// Here I initialize FormHandler. It requires the app, so I initialize it here, in index.js
// HOW TO GET THIS VAR IN CONTROLLERS?
var DataFormHandler = new (formsAngular)(app);
app.set("fh", DataFormHandler);  // THIS DOESN'T WORK. UNDEFINED in controller

app.use(kraken(options));


app.listen(port, function (err) {
    console.log('[%s] Listening on http://localhost:%d', app.settings.env, port);
});

setter app.set("fh", DataFormHandler)不起作用。当我尝试从控制器中获取fh时,它是undefined

应用\控制器\ index.js

'use strict';

var UserModel = require('../models/user');

module.exports = function (router) {

    var user = new UserModel();

    router.get('/', function (req, res) {

        var DataFormHandler = req.app.get("fh");
        DataFormHandler.addResource('user', UserModel);

        console.log("DataFormHandler", DataFormHandler);  // undefined

        var model = {
            hello: "Hello"
        }

        res.render('index', model);
    });
};

如何在控制器中获取变量?

1 个答案:

答案 0 :(得分:0)

我找到了一个有效的解决方案。但不确定这是正确的。

而不是

app.set(key, value)

哪个不起作用,我用

app.locals.key = value

由于某种原因起作用。