ng-table icon indicating copy to clipboard operation
ng-table copied to clipboard

Error: settings.$scope.$emit is not a function

Open acoard opened this issue 12 years ago • 50 comments

Hey there, just wanted to start off by saying how much I appreciate the project and the work that's been going into it.

Anyways, I seem to be having a really weird error. Basically, I can run $scope.tableParams.reload() twice with no problem, but on the third execution, and every following one, I get the following error:

TypeError: Cannot set property '$data' of null at [removed]/ng-table.js:411:55

I believe this is all the relevant code, but if anything is missing let me know:

$scope.lookupAddress = function(address){       
    var url = 'https://blockchain.info/multiaddr?cors=true&active='+address;
    $scope.loading = true;
    $scope.clearTableData();
    $http.get(url).success(function(data){
        $scope.loading = false;
        $scope.loaded = true;
        $scope.loadError = false;
        glob = data;

        //Removed code that processes the response. 

        };
        //Enables new data to be loaded, e.g. on a new address.
        //Pretty sure it's not working right now.
        if ($scope.tableParams){
            $scope.tableParams.reload();
        } 
        data = transactions; //this data var is what is called by the tables. Unsure if can remove.
        $scope.tableParams = new ngTableParams({
            page: 1,            
            count: 5,           // items per page
            sorting: {
                Date: 'desc' 
            }
        }, {
            total: transactions.length, 
            getData: function($defer, params) {
                data = transactions;
                var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));

            }
        });
    }).
    error(function(data){
        $scope.loadError = true;
    });
}

$scope.clearTableData = function(){
    transactions = [];
    $scope.output = {}
    if ($scope.tableParams){
            $scope.tableParams.reload();
    } 
}

acoard avatar Apr 29 '14 20:04 acoard

I've done some more investigating.

It seems that the speed of the callback for the third one is instant, whereas for the first two there is a delay.

By adding console.log(data) to line 406, I noticed the following behaviour: (edit: Didn't realize # links to issues in Github. Please ignore.)

  1. Returns [] at page load (with no data in table)
  2. After calling the $scope.lookupAddress() fn I wrote, it logs the data as expected a little while after the call (i.e. after the $http.get().success() events fires which takes a few moments).
  3. Calling it the second time makes steps #1 and #2 repeat in order. #1 fires immediately, and #2 with the same delay.
  4. This is where the error begins. First #1 fires, then the error detailed in the previous post. Only after the error has been fired, does #2 then fire.

After #4 happens, the table does not reload itself but the data is loaded into the backend properly. Additionally, while I can't call .reload() without getting the error, if I sort any of the columns it will update the data in the table properly.

Wow, the more I dig, the weirder this error gets.

acoard avatar Apr 29 '14 21:04 acoard

Add this to ngTableParams: $scope: { $data: {} }

as per example 14 at: http://bazalt-cms.com/ng-table/example/14

lijuenc avatar Apr 30 '14 00:04 lijuenc

Thanks for taking the time to help.

I looked over the code, and done as you've instructed. The problem isn't gone, but the error has changed. Now on the third time it says:

TypeError: undefined is not a function at [...]/ng-table.js:414:33

To be clear, that's this line:

settings.$scope.$emit('ngTableAfterReloadData');

So it seems that now that $scope is set to undefined the method call isn't working.

acoard avatar Apr 30 '14 04:04 acoard

Is there a reason why $scope.tableParams is defined inside the $http.get().success() callback, and not in the controller's function block?

lijuenc avatar Apr 30 '14 05:04 lijuenc

The $http.get().success() function is within the controller's function block. The reason $scope.tableParams is in there, is because it needs access to the data returned by $http.get().success().

Would you have handled this differently? Should I use promises? I've looked at both the example you linked and the AJAX one but haven't been able to piece it together.

acoard avatar Apr 30 '14 20:04 acoard

Looks like a scoping issue. Have success() update a controller property with the results. This will give you a reference to resolve those results for ngTable outside of success().

$scope.transactions = [];

$scope.lookupAddress = function (address) {
  var url = 'https://blockchain.info/multiaddr?cors=true&active=' + address;
  $http.get(url).success(function (data) {
    $scope.transactions = data;
    $scope.tableParams.reload();
  });
};

$scope.tableParams = new ngTableParams({
  page: 1,            
  count: 5,
  sorting: {
      Date: 'desc' 
  }
}, {
  total: $scope.transactions.length, 
  getData: function($defer, params) {
    var data = $scope.transactions;
    var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;

    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
  }
});

lijuenc avatar May 01 '14 01:05 lijuenc

Thanks again for helping me through this. I've been working on this problem all day, and hopefully I'm closer to a solution.

So, as per other threads I've seen on GitHub and StackOverflow regarding ngTables, I refactored my code to use promises instead of an $http.get().success(). So here's what it looks like now:

$scope.transactions = [];
$scope.callBlockchain = function(address) {
    var url = 'https://blockchain.info/multiaddr?cors=true&active='+address;
    var promise = BlockchainService.lookupAddress(url);
    promise.then(function(data){
        $scope.transactions = data;
        $scope.tableParams.reload();
    })

$scope.tableParams = new ngTableParams({
    page: 1,            
    count: 5,           // items per page
    sorting: {
        Date: 'desc' 
    }
}, {
    total: $scope.transactions.length, 
    getData: function($defer, params) {
        var data = $scope.transactions;
        var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));

    },
    $scope: { $data: {} }
})

When I run this I get an error, "undefined is not a function", that references line 414 of ng-table.js. Specifically it references column 33, which is right when the $emit method is being called.

If I remove $scope.tableParams.reload() then the error disappears, but the table doesn't update. Writing if ($scope.tableParams){$scope.tableParams.reload();} doesn't help rectify the problem either.

edit: Since the "undefined is not a function" error takes a half second to appear after calling the function, I'm assuming that the error only triggers after the promise is resolved (i.e. it doesn't have to do with it trying to prematurely resolve data in the promise).

edit 2: If I console.log() settings.$scope (the object which calls the $emit() method which returns undefined), I get some interesting behaviour. Upon loading the page for the first time an object is logged which looks like a normal object for the running of the module. However, after the promise in the callBlockchain() fn resolves, another object is logged which contains the data I'm trying to represent on the data.

Could this be the scoping issue you've talked about? It seems like somehow the setting data for the table is being overwritten by the content data.

acoard avatar May 01 '14 21:05 acoard

I was having the exact same issue as you guys until I figured this out.

I have a template that looks something like this:

<div ng-controller="MyController">
  <!-- an HTML form here... -->
  <button ng-click="save()" >Save and Reload</button>
</div>
<div ng-controller="MyController">
  <table ng-table="tableParams">
  <!-- my table code here... -->
  </table>
</div>

Inside MyController I have a $scope.save function that saves a new item to the service and triggers a $scope.tableParams.reload(), and also the classic $scope.tableParams = new ngTableParams(.... After breaking my head for some hours with this issue and reading ngTable's code over and over again, I found I had basically a $scope issue: 2 independent ngTableParams, one without a valid settings.$scope (the one on my controller) and another one with a valid settings.$scope (the one inside the ngTableController). When ngTable calls reload after a pagination or any other interaction, it is using the good one (the one with the valid settings.$scope) BUT when I was trying to reload the table manually, I was calling it from outside.

After understanding how the ngTable works this internally it was very simple to fix by creating the ngTableParams instance as a new factory and injecting it into the controller; that way I am 100% sure the ngTableParams instance is always the same I plan to use.

As a side note, it is NOT a good idea to set $scope: {$data: {}} because, it is not a valid $scope object and also because every time the table params change (like when moving to a different page) the ngTableController will override it with its own $scope, you can see that here

eruizdechavez avatar May 03 '14 22:05 eruizdechavez

After understanding how the ngTable works this internally it was very simple to fix by creating the ngTableParams instance as a new factory and injecting it into the controller; that way I am 100% sure the ngTableParams instance is always the same I plan to use.

@erickrdch Could you maybe elaborate on this with some code.

My HTML:

<table class="table table-condensed table-hover" ng-table="tableParams">
<!--- table stuff --->
</table>

In my controller i'm now doing this:

if (batch.rules) {
      $scope.tableParams = new ngTableParams({
          page: 1,            // show first page
          count: 25,          // count per page
          sorting: {
            created: 'desc'     // initial sorting
          }
        },
        {
          total: batch.rules.length, // length of data
          getData: function ($defer, params) {

            // use build-in angular filter
            var filteredData = $filter('filter')(batch.rules, $scope.filter);
            var orderedData = params.sorting() ?
              $filter('orderBy')(filteredData, params.orderBy()) :
              filteredData;

            $scope.rules = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());

            params.total(orderedData.length); // set total for recalc pagination
            $defer.resolve($scope.rules);
          }
        }
      );

$scope.$watch('filter.$', function () {
    $scope.tableParams.reload(); // TODO: Fix {scope: null} racecondition
});

Thanks to your post I realised the $scope.tableParams.reload() is causing the error. But how do I solve it exactly.

wilgert avatar May 13 '14 21:05 wilgert

Same issue. Have a watch on a dataset that calls $scope.tableParams.reload();

$scope.tableParams.reload() gives a Cannot set property '$data' of null the first time the watch runs (there is no existing data in the tableparams). Subsequent calls are fine.

pursual avatar May 14 '14 20:05 pursual

I just found an ugly but effective workaround. Wrap the $scope.watch in a $timeout like so:

$timeout( // Fix scope: null racecondition
  function(){
    $scope.$watch('filter.$', function () {
      $scope.tableParams.reload(); 
    });
  },
  0
);

wilgert avatar May 14 '14 21:05 wilgert

I believe this problem is caused by a race condition between the promise completing in the getData() function, and calling tableParams.reload() too early, before the promise completes. I changed my code when calling reload to this, and it seems to work fine:

  if ($scope.tableParams.data.length > 0) {
    $scope.tableParams.reload();
  }

BTW, I did not use $scope: { $data: {} } when defining my table.

Thanks for the great library.

nloyola avatar Jun 21 '14 00:06 nloyola

Is there any solution to this problem yet?

pdugar avatar Sep 05 '14 21:09 pdugar

I also had the same issue and after 2 days of a struggle managed to fix it using folliwing code line just after the

$scope.tableParams = new ngTableParams(
{...},
{...}
);
 $scope.tableParams.settings().$scope = $scope;

For more info please refer https://github.com/esvit/ng-table/blob/master/src/scripts/04-controller.js#L33

hasi avatar Sep 06 '14 05:09 hasi

Had the same problem. Hasi's solution fixed it pretty easily. Thanks!

Marcel-Malus avatar Sep 11 '14 14:09 Marcel-Malus

I too found Hasi's solution to work. However given the number of people encountering this error, might a modification to ngTable itself be in order to make things work as expected? Example 14 should simply not need the ngTableParams: $scope: { $data: {} } workaround. Any thoughts on this @esvit?

kbaltrinic avatar Sep 16 '14 13:09 kbaltrinic

First of all many thanks to the ngTable team for the great job :+1: Regarding this problem hasi'e solution worked for me too. However as kbaltrinic has also mentioned, it would be nice to have a popper fix for this issue.

elnazabo avatar Sep 16 '14 15:09 elnazabo

I have been the whole day breaking my head.. Thank you erickrdch and hasi!

tribal2 avatar Oct 05 '14 01:10 tribal2

I have the same problem, but can't piece together everyone's solution fragments to work :(. I've now got to the stage where I get the ng-table.js:414 error of $emit being undefined. In particular this is stopping the page selection code being produced (I think - something is). Does anyone have a definitive example of a post-fix solution, e.g. a plunkr? Thanks

OracPrime avatar Oct 06 '14 22:10 OracPrime

There's nothing quite like posting a question for then finding the answer seconds later. This now works for me:

$scope.activityParams = new ngTableParams({
    page: 1,            // show first page
    count: 10           // count per page
}, {
    total: 0, // length of data
    counts: [],
    getData: function ($defer, params) {
        params.total($scope.activities.length);
        $defer.resolve($scope.activities.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    },
});
$scope.activityParams.settings().$scope = $scope;

In particular the last line stops $emit being undefined (the line 414 problem). And the params.total($scope.activities.length) causes the length to correctly update when my server updates the $scope.activities values

OracPrime avatar Oct 06 '14 22:10 OracPrime