1
.run(['$rootScope', '$state', 'Session', function ($rootScope, $state, Session) {
    $rootScope.$on('$stateChangeStart', function (e, toState) {
        console.log('inside .run')
        if (toState.url == '/') {
            e.preventDefault();
            if (Session.user) { // and isAdmin == true
                $state.go('admin')
             }  //if isAdmin == false redirect to chat

            else {
                $state.go('login')
            }
        } else if (!Session.user && toState.url != '/login') {
            e.preventDefault();
            $state.go('login')
        }    

        return;
    });
}])

This is my .run module and in that i need to initialize a isAdmin variable which i can change in my controllers and check if isAdmin istrue in every state change and redirect to admin or chat page. i tried adding initializing isAdmin as $rootScope.isAdmin in .run() but before i can fix its value in controller the .run() throws isAdmin undefined error. Can anyone suggest a workaround?

Thanks in advance

Ashik Jyothi
  • 757
  • 10
  • 17

1 Answers1

0

Review below code it may accessible scope variables.Inject a service is an idle way to access variables and methods which are reusable in variable palces.

MyCtrl.js

(function () {
    'use strict'
    function MyCtrl($rootScope, $scope, MyService) {
        MyService.getRootScopeData();
        MyService.setRootScopeData('How are you?');
    }
    angular
            .module("AppRootTest")
            .controller('MyCtrl', ["$rootScope", "$scope", "MyService", MyCtrl]);
}());

MyService.js

(function () {
    'use strict'
    function MyService($rootScope) {
        function getRootScopeData() {
            console.log("$rootScope.getRooScopeData");
            console.log($rootScope.someData);
            return $rootScope.someData;
        }
        function setRootScopeData(value_) {
            $rootScope.someData = {message: value_};
        }
        return ({
            getRootScopeData: getRootScopeData,
            setRootScopeData: setRootScopeData
        });
    }
    angular
            .module("AppRootTest")
            .service("HzPopupService", ['$rootScope', MyService])
}());

app.js

angular.
    module('AppRootTest', ['ngResource','ngCookies','ngRoute','ui.router',])
    .config()
    .run(['$rootScope', function ($rootScope) {
            $rootScope.someData = {message: "hello"};
    }]);
Dipak
  • 2,248
  • 4
  • 22
  • 55