Javascript 访问全局变量

Javascript 访问全局变量,javascript,angularjs,Javascript,Angularjs,我试图在我的angularjs项目中设置一个根作用域,这样我就可以从HTML中的任何位置而不是ng视图中访问该名称 <!DOCTYPE html> <html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController"> </html> 我尝试在index.html中执行以下操作: <a href="#index" class="nav-item name_p_nav"&g

我试图在我的angularjs项目中设置一个根作用域,这样我就可以从HTML中的任何位置而不是ng视图中访问该名称

<!DOCTYPE html>
<html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController">

</html>
我尝试在index.html中执行以下操作:

<a href="#index" class="nav-item name_p_nav">{{username}}</a> 
但它只是一片空白


编辑:修复打字错误

您可以尝试类似的方法。更改声明控制器的方式。为了使用$scope变量,您必须声明它,可能您应该收到脚本错误,因为它没有声明,请使用开发人员工具在浏览器中检查以找出确切的错误

phonecatApp.controller('ApplicationController',['$scope',function ($scope){
 $scope.username = UserService.name

}])

我试图重现这个问题,我很快创建了一个应用程序,它对我起了作用!在这里,我发布了我的示例代码,请看一看

<html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController">
<head>
    <script src="../Scripts/lib/angular.min.js"></script>
    <script src="../Scripts/Application1.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
</head>
<body>
    <a href="#index" class="nav-item name_p_nav">{{username}}</a> 
</body>

打字错误function ApplicationController$scope,Username应该是function ApplicationController$scope,UserService{抱歉,是的,这是一个输入错误,但不会改变问题您是否向模块注册控制器?phonecatApp.controllerApplicationController,[$scope,UserService,ApplicationController];我已尝试将代码更改为上面的代码,但仍然没有返回,也没有错误
<html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController">
<head>
    <script src="../Scripts/lib/angular.min.js"></script>
    <script src="../Scripts/Application1.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
</head>
<body>
    <a href="#index" class="nav-item name_p_nav">{{username}}</a> 
</body>
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.factory('UserService', function(){
return {
        name : 'Tom'
};
})

function ApplicationController($scope, UserService){
$scope.username = UserService.name
}