0

I've been trying for a while and looked through several answers, I can't figure out why this is not working:

I need to share some data between controllers, so I set up a service right? (The data is obtained from a file, I'm using node-webkit)

.service('tagList', function() {

  this.getTags = function() {
    var t;

    fs.readFile('tags', 'utf8', function(err, data) {
      if (err) throw err;
      console.debug(data.split(','));
      t = data.split(',');
    });

    console.debug(t);
    return t;
  };

})

Then in some controller I'd do

.controller('sidebarCtrl', function($scope, tagList) {
  $scope.tags = tagList.getTags();
})

But tags ends up as undefined, the console.debug inside readFile both show t how it should be.

But the console.debug outside readFile, shows it as undefined, why? If it is declared on getTags scope.

Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
GGalizzi
  • 813
  • 1
  • 10
  • 18

2 Answers2

1

This could be because readFile is asynchronous. Try something like this:

.service('tagList', function($q) {
  var d = $q.defer();
  this.getTags = function() {
    fs.readFile('tags', 'utf8', function(err, data) {
      if (err) throw err;
      console.debug(data.split(','));
      d.resolve(data.split(','));
    });
    return d.promise();
  };    
})

and then use it like this:

.controller('sidebarCtrl', function($scope, tagList) {
  tagList.getTags().then(function(tags){
    $scope.tags = tags;
  });
})
Brian Lewis
  • 5,739
  • 1
  • 21
  • 28
  • Thanks, even though I'll probably stick with the sync version of `readFile` for now, your answer as taught me something which I'll probably end up using later. – GGalizzi Jan 30 '14 at 01:26
0

Nevermind, fixed it.

Problem was readFile is asynchronous, so when I was calling tags, the file wasn't read yet, so no data was stored in the variables. So I'm using readFileSync and now it works.

  this.getTags = function() {
    this.t = fs.readFileSync('tags', 'utf8');
    console.debug(this.t);
    return this.t.split(',');
  };
GGalizzi
  • 813
  • 1
  • 10
  • 18
  • doh... 17 seconds too late. I provided a way to work with the asynchronous version above, if you are interested. – Brian Lewis Jan 30 '14 at 01:20