我正在使用AngularJS制作我的第一个应用程序,我想在任何控制器之前执行run函数。

我的运行函数如下所示:

.run(function ($rootScope,authentification)
{

teamsFactory.sendAuthent().then(function(response)
{
$rootScope.authentdata=response.data;
    });
})


我进行身份验证的服务:

 teams.sendAuthent= function(DeviceID) {
    return $http({method:"POST",url:http://myserver.com/authentification",headers: {'X-SocialAPI-Service-Name': 'auth'}})
    .then(function(aResponse)
    {
    var deferred=$q.defer();
    deferred.resolve({data:aResponse.data});
    return deferred.promise;
    });
    }


这是我使用rootScope数据的控制器:

.controller('home', function($rootScope,$scope, $http,)
{



     alert($rootScope.authentdata.token);



})


但这不能正常工作,它说autehndata是未定义的,因此在运行功能之前如何执行控制器来解决该问题?

最佳答案

你可以试试看

$rootScope.$watch('authentdata', function(n, o) {
    if(angular.isDefined(n) {
        alert($rootScope.authentdata.token);
        // or alert(n.token);
    }
}

关于javascript - 如何在任何 Controller 之前执行运行功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31655935/

10-09 16:19
查看更多