angularjs 在事件中调用控制器的函数

angularjs call a function of a controller inside an event

我有一个关于 AngularJS 的问题,我在我的控制器中写了一个函数,我想在事件监听器中调用它,但是我得到了 undefinded!!

代码控制器看起来像:

inputApp.controller('my_controller', ['$scope', '$upload', '$http', '$filter', '$sce', '$timeout', 
    function ($scope, $upload, $http, $filter, $sce, $timeout) {
                $scope.changeBlock = function (block) {
                    // DO SOMETHING
                };
                $scope.$on('$locationChangeStart', function($scope, next, current){
                       // Calling the following function makes an error
                       $scope.changeBlock('Block_NAME');
                       $scope.preventDefault();                
                });
}]);

因此在 $scope.$on..... 中调用该函数会出错:

错误:$scope.changeBlock 不是函数!!

你能帮我吗,我怎样才能在那个监听器中调用我的函数?!

问候 威尔

您混淆了事件处理程序的签名并且错误地覆盖了您的 $scope 变量。事件处理程序的第一个参数是 "event" 而不是 "$scope":

这应该有效:

inputApp.controller('my_controller', ['$scope', '$upload', '$http', '$filter', '$sce', '$timeout', 
    function ($scope, $upload, $http, $filter, $sce, $timeout) {
            $scope.changeBlock = function (block) {
                // DO SOMETHING
            };

         // before:
         // $scope.$on('$locationChangeStart', function($scope, next, current){
         // now:
            $scope.$on('$locationChangeStart', function(event, next, current){
                   // Calling the following function makes an error
                   $scope.changeBlock('Block_NAME');
                   $scope.preventDefault();                
            });
}]);

将第一个参数名称:$scope$scope.$on('$locationChangeStart', function($scope, next, current){ 更改为其他名称