简体   繁体   English

访问全局变量

[英]Accessing global variables

I'm trying to set a root scope in my angularjs project so I can access name from anywhere in the HTML (not in an ng-view). 我试图在我的angularjs项目中设置一个根范围,以便可以从HTML的任何位置(而不是ng-view)访问名称。

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

</html>

That encapsulates the entire page 封装了整个页面

I've loaded in a js file called app.js with the following in; 我已经加载了一个名为app.js的js文件,其中包含以下内容:

var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.factory('UserService', function(){
    return {
        name : 'Tom'
    };
})

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

And I'm trying to do the following in the index.html: 我正在尝试在index.html中执行以下操作:

<a href="#index" class="nav-item name_p_nav">{{username}}</a> 

But it just comes back blank 但这只是空白

Edit: fixed typo 编辑:固定错别字

You can try something like this. 您可以尝试这样。 Change the way you have declared controller. 更改您声明控制器的方式。 And in order to use $scope variable, you have to declare it, probably you should be receiving script error as its not declared, please check in the browser using developer tools to find out exact error. 为了使用$ scope变量,您必须对其进行声明,可能您应收到未声明的脚本错误,请使用开发人员工具在浏览器中签入以查找确切的错误。

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

}]); }]);

I tried to reproduce issue, I quickly created an application and it worked for me! 我试图重现问题,我迅速创建了一个应用程序,它对我有用! Here, I am posting my sample code, just take a look at the same. 在这里,我将发布示例代码,让我们看一看。

<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>

Script: 脚本:

var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.factory('UserService', function(){
return {
        name : 'Tom'
};
})

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM