Luja Shrestha
Luja Shrestha

Reputation: 2877

pass variable across multiple controllers in sails

I have two controllers namely user and calendar. I have to pass user object from the user to calendar. How can we pass variable across multiple controller in sails?

Upvotes: 0

Views: 1498

Answers (3)

wizopunker
wizopunker

Reputation: 11

I'm just starting with sails (and node.js generally speaking), but I'm fearly common with javascript (client sided).

The only way I found out was using the variable scope. If you declare a variable before any anonymous function, you'll be able to edit this variable from inside the function. So inside your action in your controller you'll have something like :

        //this will allow me to store my informations inside the categories variable.
        var categories;
        Categories.find().done(function(err, cat){
            categories = cat;
        });

        //calling another datas and passing them to the view, alongside with my previous datas
        Categories.findOne(id).done( function(err, cat){
            return res.view({
                data : cat,
                cats : categories
            });
        })

I'm sure they're a lot of better ways, and I'm interested in knowing them =)

Upvotes: 1

JohnGalt
JohnGalt

Reputation: 2881

In your CalendarController.js:

module.exports = {

foo: function(req, res, next) {

    User.findOne(2).exec(function(err, user) {

        if (err) return next(err);

        res.json(user);

    });
},


/**
 * Overrides for the settings in `config/controllers.js`
 * (specific to CalendarController)
 */
_config: {}

};

Upvotes: 0

bredikhin
bredikhin

Reputation: 9045

Off the top of my head, I would say that you could use session. Though in terms of design, a situation when you are passing a variable from one controller to another should be really questionable.

Upvotes: 0

Related Questions