Lemon
Lemon

Reputation: 199

Passing data from controller to another controller

I am working on sails JS application.

Is there anyway to pass a data from another controller using sails JS?

  // controller 1
  exports.module{
     passing data to controller 2
  }

  // controller2 

  exports.module{
     get data from controller 1
  }

or better, is there anyway to create a global variable which can be accessed by any controller in sails js? just like $_SESSION['sessionname'] in php?

Upvotes: 1

Views: 362

Answers (2)

bhapri
bhapri

Reputation: 119

I will assume there are two Controller as you have asked in your question.

Subject Controller (which returns the data)

module.exports = {
  science : function (req, res, next, callback) {
    var data = ["Biology", "Physics", "Chemistry"];
    return callback(data);
  }
}

Student Controller (which receives the data)

module.exports = {
  getStudentSubject : function(req, res, next, callback){
    //get the data from Subject controller
    sails.controllers.subject.science(req, res, next, function(data){
      // got the data
      console.log(data)
      // this should print ["Biology", "Physics", "Chemistry"]
    });
  }
}

Any controller method can be accessed in sails by sails.controllers.methodName

Hope this helps.

Upvotes: 0

M-A. Fernandes
M-A. Fernandes

Reputation: 550

You can use a Service, it enables you to access data everywhere in your code.

EDIT

You can also use the global variable sails:

sails.myObject = {}

Upvotes: 2

Related Questions