如何在angularJS中创建全局变量 [英] How to make global variables in angularJS

查看:94
本文介绍了如何在angularJS中创建全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,当您注册时会进入用户"页面.并假设说欢迎",原因是我不确定该用户名是否显示在网页上"……请帮助这里是plunkr:

i have this problem where when you register you get to the Users page. And its suppose to say "Welcome " The username dosent show up for On The Webpage for reason im not to sure about... please help here is the plunkr:

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

请我需要帮助.

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

i need to get some code for plunker so : 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;
      });
    };*/
  }
]);

推荐答案

您的代码中可能要处理很多事情,但是有一些快速且部分肮脏的解决方案:

There are many things in your code that you might want to take care of, but some quick and partially dirty solutions:

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

Do not include all of your javascript files on your nested templates. Anything that is routed to in your ng-view should just be the html you want to be inserted within that <div>. No CSS links, no script tags, nothing but HTML that would normally be within the body of a page.

在您的注册页面上,您的用户名ng-model需要与您作为参数传递给ng-click的内容匹配.因此,您需要将其替换为ng-model="username"来匹配ng-click="createUser(username, email, password)".

On your registration page, your username ng-model needs to match what you are passing as an argument to your ng-click. So instead of ng-model="userName" you need it to be ng-model="username" to match ng-click="createUser(username, email, password)".

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

Your other major issue is that $scope is being overwritten each time you change views because each one of your routes has the same controller. So conceptually, you may be thinking that the username (which you have stored as the plural $scope.usernames for some reason) is there for you to access still on $scope. But that is not the case, as each view is running on its own unique instance of the Auth Controller. The quickest solution since you don't know how to implement services is probably to inject $rootScope into your controller, and then put usernames on $rootScope instead of $scope (though keep in mind using $rootScope in production is considered bad practice), as $rootScope will persist across all of your controllers. So your javascript file would look more like this:

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

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

然后

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

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

这篇关于如何在angularJS中创建全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆