初始化依赖于卸载依赖项的控制器

时间:2013-07-02 21:00:13

标签: angularjs

使用ui-router我创建了一个状态,其中一个视图显示当前用户状态。以下代码获取当前用户状态:

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");
    }
}

state定义为:

$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'
        }
    }
})  

LoginController

function LoginController($scope, $state) {
    $scope.checkUserStatus = function() {
        sydney.checkAuth();
    }
}

我需要粘贴所有这些部分,所以当显示headerView时,我可以显示用户状态(登录与否)。

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

$scope.userStatus = sydney.checkAuth();

问题是sydney.checkAuth依赖Google APIs Client Library for JavaScript,而LoginController在创建gapi is not defined时未加载。所以我得到$scope.userStatus完全有道理。

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

1 个答案:

答案 0 :(得分:0)

这种问题的方法很少。

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

具体来说,使用$broadcast解耦组件,并允许您在多个位置使用该事件 - 如果您需要更新除标题之外的其他位置。