TypeError:无法调用方法'$在'的未定义

TypeError: Cannot call method '$on' of undefined

本文关键字:未定义 调用 方法 TypeError      更新时间:2023-09-26

这是我在angular应用中的controller.js代码

function MyCtrl1($scope) {
  $scope.$on('$locationChangeStart', function (event, next, current) {
    event.preventDefault();
    var answer = confirm("Are you sure you want to leave this page?");
    if (answer) {
      $location.url($location.url(next).hash());
      $rootScope.$apply();
    }
  });
}
MyCtrl1.$inject = [];

function MyCtrl2() {}
MyCtrl2.$inject = [];

当我签入chrome时,我在开发者控制台中得到了以下错误

TypeError: Cannot call method '$on' of undefined

任何人都能指出可能出了什么问题吗。

您需要注入$scope。

MyCtrl1.$inject = ['$scope'];

编辑:完全修复

如果您使用ctrl.$inject = []; 显式注入,那么您将需要注入任何传入控制器的内容

function MyCtrl1($scope, $location, $rootScope) {
  $scope.$on('$locationChangeStart', function (event, next, current) {
    if (!confirm("Are you sure you want to leave this page?")){
      event.preventDefault();
    }
  });
}
MyCtrl1.$inject = ['$scope', '$location', '$rootScope'];