如何从角度js调用javascript方法?

时间:2015-03-31 12:10:37

标签: javascript jquery angularjs html5

当声音结束时,我需要从angular.js调用JavaScript方法。我想调用check()方法中的ready函数。

app.controller("myCtrl",function($scope,ngAudio,$document)
    {
        $scope.audio;
        $scope.play=function(myAud)
        {
            $scope.audio = new Audio(myAud)
            $scope.audio.play();
            $scope.audio.onended=function()
            {
                console.log("called");
                $scope.audio = new Audio('aud1.mp3');
                $scope.audio.play();
                $scope.check();
            }
        }
        $scope.stop=function()
        {
            $scope.audio.stop()
        }
         $document[0].addEventListener("visibilitychange", function() {
        var doucmentHidden = document.hidden;
        if (doucmentHidden)
        {
            console.log("called");
            $scope.audio.pause();
        }
        else
        {
            console.log("called");
            $scope.audio.play();
        }
        }, false);
    });
    </script>
    <script>
        $(document).ready(function()
        {
            var aud= angular.element(document.getElementById('container')).scope();
             aud.play('aud.mp3');
                 function check()
                 {
                    console.log("called1");
                }
        });
    </script>

如何在需要时触发check()功能?

1 个答案:

答案 0 :(得分:1)

正如我所看到的,check()函数位于不同的script块中且位于不同的范围内。相反,你应该把它放在控制器的范围内,以便可以使用它:

    app.controller("myCtrl", function($scope, ngAudio, $document) {
      $scope.audio;
      $scope.check = function(){ // declare it here.
          console.log('check called on end.');
      };
      $scope.play = function(myAud) {
        $scope.audio = new Audio(myAud)
        $scope.audio.play();
        $scope.audio.onended = function() {
          $scope.check(); // now it can use the check function from the $scope
        }
      }
      $scope.stop = function() {
        $scope.audio.stop()
      }
      $document[0].addEventListener("visibilitychange", function() {
        var doucmentHidden = document.hidden;
        if (doucmentHidden) {
          console.log("called");
          $scope.audio.pause();
        } else {
          console.log("called");
          $scope.audio.play();
        }
      }, false);
    });
     // remove the script tags and put both in a same script block 
    $(document).ready(function() {
      var aud = angular.element(document.getElementById('container')).scope();
      aud.play('aud.mp3');
    });