如何在angularJS中创建全局变量

时间:2016-01-10 02:44:51

标签: angularjs

我有这个问题,当你注册时,你进入用户页面。它假设说"欢迎"用户名dosent显示在网页上因为我不确定...请帮助这里是plunkr:

http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH?p=preview

我需要帮助..

我需要为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;
      });
    };*/
  }
]);

3 个答案:

答案 0 :(得分:3)

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

将持久性数据与创建该数据的函数一起存储在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);
          };
     };
   }
]);

这样,当您更改路线时,数据会保留并保持不变。

答案 1 :(得分:2)

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

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

在您的注册页面上,您的用户名ng-model需要与您作为参数传递给ng-click的内容相匹配。因此,ng-model="userName"代替ng-model="username"而不是ng-click="createUser(username, email, password)"来匹配$scope

您的另一个主要问题是每次更改视图时都会覆盖username,因为每个路由都有相同的控制器。因此,从概念上讲,您可能会认为$scope.usernames(由于某种原因,您已存储为复数$scope)可供您在$rootScope上访问。但事实并非如此,因为每个视图都在其自己的Auth Controller实例上运行。您不知道如何实施服务的最快解决方案可能是将usernames注入您的控制器,然后将$rootScope放在$scope而不是$rootScope上(虽然记住在生产中使用app.controller("AuthCtrl", ["$scope", "$rootScope", "Auth", function($scope, $rootScope, Auth) {被认为是不好的做法),因为$ rootScope将在所有控制器中保持不变。所以你的javascript文件看起来更像是这样:

$scope.createUser = function(username, email, password) { $rootScope.usernames = username $scope.message = null; $scope.error = null;

然后

many-to-many

答案 2 :(得分:1)

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

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

相关问题