Tarrence
Tarrence

Reputation: 794

Watch not being called on array push

I have a service for PeerJS that contains an array of active streams. When setting up a WebRTC stream there is a callback that is called when the stream becomes available

call.on('stream', function(stream){
    activeStreams.push(URL.createObjectURL(stream));
  });

When a stream is available I push it onto the activeStreams array. I then watch this array value in my controller like this:

//PeerRTC is the service and .getActiveStreams returns the activeStreams array
$scope.$watch(PeerRTC.getActiveStreams, function(activeStreams) {
  $scope.activeStreams = activeStreams;
}, true);

But for some reason the watch callback doesn't execute when I push a url(string) value to the array.

Am I overlooking something? Could it be because the activeStreams value is changing in a callback function?

Upvotes: 0

Views: 111

Answers (3)

Iqbal Fauzi
Iqbal Fauzi

Reputation: 1571

Some condition, like async call, you will need to call $scope.apply() to make it work. Try call it right after you push the new data to the array.

Upvotes: 1

user1852503
user1852503

Reputation: 5607

What is "PeerRTC.getActiveStreams"?

By the naming it looks like a function, not an array. (it is a varb).

If it is a function that gets the array, you have to watch the result of invoking the function, not the function itself. as the function stays the same.

$scope.$watch('PeerRTC.getActiveStreams()', function(activeStreams) {
  $scope.activeStreams = activeStreams;
}, true);

also make sure the array is on the scope.

Upvotes: 0

Jorg
Jorg

Reputation: 7250

I've always used the watch variable as an expression string:

$scope.$watch('PeerRTC.getActiveStreams', function(activeStreams) {
  $scope.activeStreams = activeStreams;
}, true);

doco.

Upvotes: 0

Related Questions