Angularjs Init依赖于已卸载依赖项的控制器

Angularjs Init依赖于已卸载依赖项的控制器,angularjs,Angularjs,通过ui路由器我创建了一个状态,其中一个视图显示当前用户状态。以下代码获取当前用户状态: var sydney = sydney || {}; sydney.checkAuth = function() { gapi.auth.authorize({ client_id : sydney.CLIENT_ID, scope : sydney.SCOPES, immediate : true }, sydney.handleAuthRe

通过
ui路由器
我创建了一个状态,其中一个视图显示当前用户状态。以下代码获取当前用户状态:

var sydney = sydney || {};
sydney.checkAuth = function() {
    gapi.auth.authorize({
        client_id : sydney.CLIENT_ID,
        scope : sydney.SCOPES,
        immediate : true
    }, sydney.handleAuthResult);
}

sydney.handleAuthResult = function(authResult) {
    if (authResult) {
        // The user has authorized access
        console.log("User is signed in");
    } else {
        // User has not Authenticated and Authorized
        console.log("User is not signed in");
    }
}
状态
定义为:

$stateProvider
.state('route1', {
    url: "/route1",
    views : {
        "headerView" : {
            templateUrl : 'partials/header.html',
            controller: 'LoginController'
        },
        "navigationView" : {
            templateUrl : 'partials/navigation.html',
            controller: 'NavigationController'
        },
        "contentView": {
            templateUrl : 'partials/content1.html'
        }
    }
})  
登录控制器

function LoginController($scope, $state) {
    $scope.checkUserStatus = function() {
        sydney.checkAuth();
    }
}
我需要粘合所有这些部分,这样当显示
headerView
时,我可以显示用户状态(登录或未登录)

我做的第一件事是在
LoginController
中创建一个变量来保存状态

$scope.userStatus = sydney.checkAuth();
问题在于
sydney.checkAuth
依赖于
Google api客户端库for JavaScript
,该库在创建
LoginController
时未加载。所以我得到的是,gapi没有定义,这完全有道理


另一个解决方案是在加载
gapi
后(在回调中)初始化
$scope.userStatus
。但是如何告诉控制器更新
$scope.userStatus

对于此类问题,几乎没有不同的方法

在类似的情况下,我成功地使用
$rootScope
注入
$broadcast
从依赖项发送事件,即
gapiSetup
-然后可以根据需要在控制器、服务等中提取该事件

具体来说,使用
$broadcast
可以解耦组件,还允许您在多个位置使用该事件,就像您需要更新除标题之外的其他位置一样