简体   繁体   中英

TypeError: Cannot call method '$on' of undefined

Here is my controller.js code in angular app

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 = [];

When i checked in chrome i got the following error in developer console

TypeError: Cannot call method '$on' of undefined

can any one point out what may be wrong.

You need to inject $scope.

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

EDIT: The full fix...

Anything you're passing into your controller, you're going to need to inject, if you're injecting explicitly with 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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM