sonicblis sonicblis - 3 months ago 13
AngularJS Question

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

Relevant fiddle: https://jsfiddle.net/tqf4zea7/1/

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){
$timeout(function(){
resolve(valToReturn);
}, 500);
});
}


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

returnAPromise('third').then($scope.messages.push);


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:

returnAPromise('third').then(function(message){
$scope.messages.push(message)
});


Is this a closure issue I don't understand?

Answer

You need to bind push since it uses this

returnAPromise('third').then($scope.messages.push.bind($scope.messages));