0

I'm waiting until the data has been retrieved and then adding the data to the table and (trying to) add a click event to each row with the following code.

scope.$watch(attrs.aaData, function(value) {
  var completeData = scope.$eval(attrs.allData);
  var dataTable = element.dataTable(options);
  var val = value || null;
  if (val) {
    dataTable.fnClearTable();
    dataTable.fnAddData(scope.$eval(attrs.aaData));
    var table = document.getElementsByClassName("dataTable")[1];
    for (var i = 0, row; row = table.rows[i]; i++) {
      console.log(row);
      console.log(completeData[i]);
      $(row).click(function(){
        window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
      })
      // javascript for click, but there should be a ng-click way
      // $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
    };
  }

The console log confirms the row and completeData[i] are returning the correct values (and completeData[i]) has the patient_id component I want. Yet, when I click any row I get the following error:

Uncaught TypeError: Cannot read property 'patient_id' of undefined 

Any ideas?

Morgan
  • 1,438
  • 3
  • 17
  • 32

1 Answers1

1

The issue is a scoping issue. You need to wrap your event handler in a closure.

for (var i = 0, row; row = table.rows[i]; i++) {
  (function(i) {
    console.log(row);
    console.log(completeData[i]);
    $(row).click(function(){
      window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
    })
    // javascript for click, but there should be a ng-click way
    // $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
  })(i);
}

Because as it stands now, this line:

    $(row).click(function(){
      window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
    })

will always refer i to the current value of i, not the value it had when the function was defined.


Alternatively, I recommend using jquery's $.each to clean up your loop and also build a closure at the same time:

$.each(table.rows, function(i, row) {
  console.log(row);
  console.log(completeData[i]);
  $(row).click(function(){
    window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
  })
  // javascript for click, but there should be a ng-click way
  // $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
});
Community
  • 1
  • 1
000
  • 26,951
  • 10
  • 71
  • 101