如何在angularJS中生成全局变量

如何在angularJS中生成全局变量,angularjs,Angularjs,我有一个问题,当你注册时,你会进入用户页面。而且它假设说“欢迎”这个用户名会出现在网页上,因为我不确定。。。请在这里提供帮助,这是plunkr: 我需要帮助 我需要为plunker获取一些代码,以便: script.js: var app = angular.module('LoginApp', ["firebase", "ngRoute"]) app.config(function ($routeProvider) { $routeProvider .when('/',

我有一个问题,当你注册时,你会进入用户页面。而且它假设说“欢迎”这个用户名会出现在网页上,因为我不确定。。。请在这里提供帮助,这是plunkr:

我需要帮助

我需要为plunker获取一些代码,以便: script.js:

var app = angular.module('LoginApp', ["firebase", "ngRoute"])

app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'registration.html',
        controller: 'AuthCtrl'
      })
      .when('/logIn', {
        templateUrl: 'login.html',
        controller: 'AuthCtrl'
      })

      .when('/User', {
        templateUrl: "User.html",
        controller: 'AuthCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });


  });


app.factory("Auth", ["$firebaseAuth",
  function($firebaseAuth) {
    var ref = new Firebase("https://uniquecoders.firebaseio.com/");
    return $firebaseAuth(ref);
  }
]);


app.controller("AuthCtrl", ["$scope", "Auth",
  function($scope, Auth) {


      $scope.createUser = function() {

        $scope.message = null;
        $scope.error = null;
    var ref2 = new Firebase("https://uniquecoders.firebaseio.com/");
  ref2.createUser({
    email: $scope.email,
    password: $scope.password
  }, function(error, userData) {
    if (error) {
      switch (error.code) {
        case "EMAIL_TAKEN":
          alert("The new user account cannot be created because the email is already in use. Try to login");
          break;
        case "INVALID_EMAIL":
          alert("The specified email is not a valid email.");
          break;
        case "INVALID_PASSWORD":
          alert("The Specified Passowrd Is not valid.")
          break;
        default:
          alert("Error creating user:", error);
      }
    } else {
      alert("Successfully created user account with uid:", userData.uid);
      alert($scope.UserName)

      window.location.hash = "/User"
       $scope.usernames = "HEY"
    }
  });


      };

       $scope.logIn = function(){
        $scope.message = null;
        $scope.error = null;

        ref2.authWithPassword({
          "email" : $scope.logInemail,
          "password" : $scope.logInemailpassword

        }, function(error, userData){

          if(error){
            alert("Login Failed.")
            console.log(error)
          }
          else{
            alert("Logged In!")
          }

        })

      }

  /*  $scope.removeUser = function() {
      $scope.message = null;
      $scope.error = null;

      Auth.$removeUser({
        email: $scope.email,
        password: $scope.password
      }).then(function() {
        $scope.message = "User removed";
      }).catch(function(error) {
        $scope.error = error;
      });
    };*/
  }
]);

当您导航到用户视图时,angular将创建AuthCtrl控制器的新实例,这意味着新范围,这就是其中没有值的原因


使用服务在控制器之间共享数据(甚至范围)。

当应用程序更改路由时,它会破坏旧控制器的范围并创建新范围。即使对旧路线和新路线使用相同的控制器,也会发生这种情况

将持久数据与创建该数据的函数一起存储在
Auth
工厂中

app.factory("Auth", ["$firebaseAuth",
  function($firebaseAuth) {
    var AuthObj = {};
    //Store persistent data on AuthObj
    AuthObj.ref = new Firebase("https://uniquecoders.firebaseio.com/");
    AuthObj.createUser = function(email,password) {
        AuthObj.ref.createUser(
            {email: email, password: password },
            function(error, userData) {
                if (error) {
                    //process error
                } else {
                    //store data on AuthObj
                    AuthObj.userData = userData;
                }
             }
        );
        return AuthObj.userData;
    };
    //return AuthObj which holds functions and data
    return AuthObj;
  }
]);
使用控制器调用这些函数并检索持久数据

app.controller("AuthCtrl", ["$scope", "Auth",
  function($scope, Auth) {
     //retrieve userData
     $scope.userData = Auth.userData;
     $scope.createUser = function() {
          if ($scope.userData) {
              return;
          } else {
              $scope.userData =
                   //invoke function in factory
                   Auth.createUser($scope.email,$scope.password);
          };
     };
   }
]);

这样,当您更改路由时,数据将保持不变。

您的代码中有许多内容可能需要处理,但有些是快速且部分脏的解决方案:

不要在嵌套模板中包含所有javascript文件。在
ng视图中路由到的任何内容都应该是要插入该
中的html。没有CSS链接,没有脚本标签,只有通常在页面主体中的HTML

在注册页面上,用户名
ng model
需要与作为参数传递给
ng click
的内容相匹配。因此,您需要将其设置为
ng model=“userName”
而不是
ng model=“userName”
以匹配
ng click=“createUser(用户名、电子邮件、密码)”

您的另一个主要问题是,每次更改视图时,
$scope
都会被覆盖,因为您的每条路线都有相同的控制器。因此,从概念上讲,您可能认为
用户名
(出于某种原因,您将其存储为复数
$scope.usernames
)仍然可以在
$scope
上访问。但事实并非如此,因为每个视图都在其自身唯一的Auth控制器实例上运行。由于您不知道如何实现服务,最快的解决方案可能是将
$rootScope
注入控制器,然后将
用户名
放在
$rootScope
上,而不是
$scope
(尽管请记住在生产中使用
$rootScope
被认为是不好的做法),因为$rootScope将在所有控制器上持久存在。因此,您的javascript文件看起来更像这样:

app.controller(“AuthCtrl”、[“$scope”、“$rootScope”、“Auth”,
函数($scope,$rootScope,Auth){

然后

$scope.createUser=函数(用户名、电子邮件、密码){
$rootScope.usernames=用户名
$scope.message=null;

$scope.error=null;

我想你需要学习更多关于angular的知识:寻找服务和作用域。@ViníciusFagundes你能帮我吗thoguh?对不起。这类问题应该解决。有几种方法可以回答。从长远来看,你会想学习如何使用服务而不是$rootScope。在短期内,你会想确保你的每个视图都有一个不同的控制器。非常感谢P Ackerman。你的视图是一个救命稻草!你还有什么其他建议吗?我正在制作一个带有登录/注册的待办事项列表网站。如果它不困扰你P Ackerman,你知道如何只为特定用户实现数据吗?非常感谢!我我对如何在我的代码中实现这一点感到困惑。很抱歉,当我写答案时,我的目标是创建对多个读者有用的东西。所以当有人搜索“AngularJS全局变量”时,他们会得到他们可以使用的建议。在这种情况下,建议是--将永久性数据放入工厂提供程序中。要了解更多有关工厂提供程序的信息,请参阅。我了解george,但我不想了解如何将Prestant数据放入工厂中。如果您有其他选择,我将非常乐意使用此实用程序。谢谢你。在我的一个单独问题中,该应用程序的登录不起作用。我不知道为什么