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

angularjs call a function of a controller inside an event

本文关键字:一个 函数 调用 事件 控制器 angularjs      更新时间:2023-09-26

我对AngularJS有一个问题,那就是我在控制器中编写了一个函数,我想在事件列表中调用它,但我没有定义!!

代码控制器看起来像:

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内调用该函数$上…..犯错误:

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

你能帮我吗,我怎么才能在那个列表中调用我的函数?!

问候Wael

您混淆了事件处理程序的签名,并且错误地覆盖了$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){更改为其他