sonicblis sonicblis - 1 year ago 85
AngularJS Question

Why is $scope.someArray.push not a valid function to pass to .then on $q.promise

Relevant fiddle:

I'm using $q in an angular controller. To test some scenarios, I created an array on the scope to push messages to:

$scope.messages = [];

I have set up a function that returns a $q function as so:

function returnAPromise(valToReturn){
return $q(function(resolve, reject){
}, 500);

I then have a
call on the result that looks like this:


Since I only want to push the value that the promise was resolved with to the array, I figured I could just pass in the push method of the messages array, but when I do that, I get the following error:

VM289 angular.js:12520 TypeError: Array.prototype.push called on null or undefined
at processQueue (VM289 angular.js:14792)
at VM289 angular.js:14808
at Scope.$eval (VM289 angular.js:16052)
at Scope.$digest (VM289 angular.js:15870)
at Scope.$apply (VM289 angular.js:16160)
at VM289 angular.js:17927
at completeOutstandingRequest (VM289 angular.js:5552)
at VM289 angular.js:5829

If I enclose push in a function, it works fine:


Is this a closure issue I don't understand?

Answer Source

You need to bind push since it uses this

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download