【问题标题】:TypeError: Cannot call method '$on' of undefinedTypeError:无法调用未定义的方法'$on'
【发布时间】:2013-02-12 16:29:00
【问题描述】:

这是我在 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

谁能指出哪里出了问题。

【问题讨论】:

  • 试试console.log($scope)

标签: javascript angularjs angularjs-directive


【解决方案1】:

你需要注入 $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'];

【讨论】:

  • 成功了,但现在出现另一个错误 ReferenceError: $location is not defined
  • 你还需要注入$location,这是另一个服务。
  • 添加了更全面的答案。
  • 这次又出现了一个新错误错误:$digest 已经在进行中
  • 似乎这个问题真的不止一个问题。大声笑
猜你喜欢
  • 1970-01-01
  • 2012-11-12
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多