AngularJS - 使整个应用程序可以访问变量

时间:2015-03-14 03:49:25

标签: javascript angularjs firebase

以下是与Firebase数据库连接的一段代码。

我有numberOfUsers的值,现在我想在html中使用这个变量,如{{numberOfUsers}}。

我不确定最好的方法,或者我是否还需要使用控制器?对不起,如果这是一个愚蠢的问题,我还在学习Javascript和Angular。

angular.module('myApp', ['ngRoute', 'firebase'])

  var userList = new Firebase("https://my-app.firebaseio.com/presence/");

  userList.on("value", function(snap) {
    numberOfUsers = snap.numChildren();
    console.log("Users = " + numberOfUsers);
  });

;

http://jsfiddle.net/HB7LU/11820/

非常感谢任何帮助。

由于

3 个答案:

答案 0 :(得分:2)

使值可用的正式方法是将其放在$ rootScope中,但最好将其作为服务的一部分公开。

答案 1 :(得分:1)

尝试使用常量

http://jsfiddle.net/HB7LU/11818/

var myApp = angular.module('myApp',[]);

    myApp.constant('numUsers', 4);

    function MyCtrl($scope,numUsers) {
        $scope.name = 'Superhero';
        $scope.numUsers = numUsers;

        $scope.addUser = function(){
            numUsers++;
            $scope.numUsers = numUsers;
        }
    }

答案 2 :(得分:0)

您可以使用常量来实现与Lucas建议的相同。但是,不是为每个值创建一个常量服务,而是可以将它们组合在一起,如下所示:

angular.module("myModule")
.constant("CONST", { "KEY1" : "VALUE1", 
    "KEY2" : "VALUE2"});

通过这种方式,您可以将一堆常量聚集在一起并使用它:

CONST.KEY1
CONST.KEY2

编辑:您的问题似乎非常不同。

首先,您应该使用Firebase的AngularJS风格。它被称为AngularFire。您可以找到有关它的更多信息here。我将回答基于模型更改呈现UI的问题。 AngularJS推广MVC模式。您需要服务,控制器和视图对象(HTML页面)来实现您想要的功能。

在我在下面提供的示例中,所有内容都被分成一个文件(index.html),但理想情况下,代码应该分开。

<div ng-app="myapp">
    <div ng-controller="PostCtrl" >
        <ul>
            <li ng-repeat="post in posts"> <!-- $scope.posts of PostCtrl" -->
                <div>
                    <span>{{post}}</span> <!-- {{}} is used to render data -->
                </div>
           </li>
       </ul>
   </div>
    <script>
        //factory is a type of service. Services are used to write business logic or fetch data from the backend. Your Firebase related calls should come here. 
        angular.module("myapp", []).factory("myService", function($http) {
         return { 
          fetchData: function() { 
        return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; //can also be a request to the backend returning data.
          }
         };
        });

         //a controller connects a service to the HTML file. $scope service provided by AngularJS is used to achieve this.
        angular.module("myapp").controller("PostCtrl", ["$scope", "myService", function($scope, myService) {
         //posts variable is used in HTML code to retrieve this data.
         $scope.posts = myService.fetchData();
        }]);
    </script>
</div>

要了解AngularJS的基础知识,您可以浏览codeschool教程。它们是互动的,从基础开始。

相关问题