1

I want to constantly monitor the value of a global variable from Angular. I have a flash movie which records microphone data and pushes this out to the global variable. I reference this variable from Angular like this:

$scope.audioData = $window.audioData;
$scope.$watch('audioData', function() {
    console.log("audio in angular!:", $scope.audioData.length);
});

and in the HTML I've put:

<h1>{{audioData.length}}</h1>

In the HTML I can see that the audio data is changed after I recorded, but the watch function is not being called while it's recording, which I need to stream the audio to a server.

3
  • 1
    watch audioData.length, or use the third parameter to $watch. Commented May 3, 2013 at 11:48
  • Unfortunately this doesn't work. The function is still only being called after the recording is stopped (button is clicked). Commented May 3, 2013 at 11:54
  • 1
    you'll probably also want to use $apply somewhere. Commented May 3, 2013 at 11:56

1 Answer 1

2

There are two things to keep in mind here.

The first is that $watch by default only watches the identity of objects and array, so it doesn't notice if there are changes inside the value. This can be solved by watching the length or using the third argument as Yoshi has mentioned.

The second thing to remember is that Angular will only check its watches when something triggers it. If nothing is happening in Angular-world, then no watches or callbacks will be executed. Since your recorder lives outside of the Angular-world, it needs to notify Angular that something has been changed. This can be done by calling $apply occasionally after updating the recording. An alternate way to consider is to just have Angular update at regular intervals by using $timeout.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works! Is it also possible to directly call a function on the scope of the controller outside of angular? If I retrieve the scope with angular.element(e).scope(), where e is the top element that gets loaded inside ng-view, I cannot seem to be able to call the functions within the assigned controller.
@JoostVanDoremalen Not sure, but maybe $eval() can help you. The proper solution though is to wrap all this stuff in a directive, but that's a little more work, especially if you're not used to doing it yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.