iJade
iJade

Reputation: 23811

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.

Upvotes: 1

Views: 2488

Answers (1)

Ben Lesh
Ben Lesh

Reputation: 108501

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'];

Upvotes: 1

Related Questions