0

I am writing an AngularJS web app and have a function outside of any scope that needs to call a function inside of a scope. I call the function and follow the instructions given in this answer.

function returnDest(callback) {
$(document).ready(angular.element(document.getElementById('body')).scope().getTask(function() {
    if(callback) {
        callback(locationInfo);
    }
}));
}

It works often, but sometimes the function does not successfully run. A debugger gives me:

Uncaught TypeError: Cannot read property 'getTask' of undefined

I do not know why the function is being called on undefined when $(document).ready should have the function fire only after the DOM has been loaded. The same error pops up if I use $(window).load(). What can I do to ensure this function runs successfully?

For reference, here is the line in the HTML file where the 'body' element is defined

<body style="background-color:#e6e8f3" ng-app="app" ng-controller="controller" id="body">
Community
  • 1
  • 1
jcharch
  • 150
  • 16

3 Answers3

2

$(document).ready should be outside of your function:

$(document).ready(function returnDest(callback) {
angular.element(document.getElementById('body')).scope().getTask(function() {
    if(callback) {
        callback(locationInfo);
    }
})});
0

angular.element returns a jQuery object.

ready() expects the argument you pass it to be a function that it will call when the document is ready.

It sounds like you need to wrap everything you are trying to pass to ready in function () { ... }.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You're using .ready incorrectly. The moment you call returnDest, which is happening before the DOM is ready, it tries to get an element with the ID of body. Since it's not loaded, body can't be accessed. Instead, omit the body ID and use it like this:

function returnDest(callback) {
  $(document).ready(function() {
    angular.element(document.body).scope().getTask(function() {
      if (callback) {
        callback(locationInfo); // Not sure where locationInfo is coming from
      }
    });
  });
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • Fantastic, this worked perfectly for what I needed. Trying to understand this further though, I understand that the main reason why the code I posted didn't work was because I didn't wrap the call to getTask inside a function. Does it make any difference whether I use document.body, or document.getElementById('body')? – jcharch Jan 25 '16 at 18:04
  • @jcharch The only real difference is you don't have to give the body an ID and it's shorter to write ;) – Mike Cluck Jan 25 '16 at 18:05