Adrian Marinica
Adrian Marinica

Reputation: 2201

Get $scope reference on $rootScope event handler

In the .run section of the main module of my application, I have an event handler for the $locationChangeStart event. I want to use this in order to confirm discarding unsaved changes. The problem is that I need a reference to the $scope in order to perform these checks.

I tried adding that reference as I added the one for the $rootScope, but I get an error Uncaught Error: Unknown provider: $scopeProvider <- $scope.

How should I proceed to this? I am open for alternatives.

.run(['$rootScope', '$location', function ($rootScope, $location) {
    $rootScope.$on("$locationChangeStart", function (event, next, current) {
        if ($scope.unsavedChanges && !confirm('Unsaved changes') {
            event.preventDefault();
        }
    });
 }

Upvotes: 0

Views: 1095

Answers (2)

zs2020
zs2020

Reputation: 54543

You can only inject instances (not Providers) into the run blocks. This is from the doc of module.

angular.module('myModule', []).
    run(function(injectables) { // instance-injector
        // This is an example of a run block.
        // You can have as many of these as you want.
        // You can only inject instances (not Providers)
        // into the run blocks
    });

So you won't be able to inject $scopeProvider.

Upvotes: 1

BKM
BKM

Reputation: 7079

You could inject $scope to your function like;

 .run(['$rootScope', '$location', '$scope', function ($rootScope, $location, $scope)

Upvotes: 0

Related Questions