如何在任何控制器之前执行Run函数

时间:2015-07-27 14:31:16

标签: javascript angularjs

我使用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是未定义的,所以控制器在运行函数之前执行如何解决?

1 个答案:

答案 0 :(得分:1)

你可以试试这个,

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