如何使角度全局变量 [英] How to make global variables in angular

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

问题描述

玉家伙,所以我有这样的问题,即当你注册你的用户页面。而其假设说欢迎用户名dosent显示出于某种原因......请帮助这里是plunkr:

<一个href=\"http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH?p=$p$pview\">http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH?p=$p$pview

请我需要帮助。

我需要得到一些code为plunker这样:
的script.js:

  VAR应用= angular.module('LoginApp',[火力点,ngRoute])的app.config(函数($ routeProvider){
    $ routeProvider
      。什么时候('/', {
        templateUrl:registration.html',
        控制器:'AuthCtrl
      })
      。当('/登录',{
        templateUrl:'的login.html',
        控制器:'AuthCtrl
      })      。当('/用户',{
        templateUrl:User.html
        控制器:'AuthCtrl
      })
      。除此以外({
        redirectTo:'/'
      });
  });
app.factory(验证,[$ firebaseAuth
  功能($ firebaseAuth){
    VAR REF =新的火力地堡(HTTPS://unique$c$crs.firebaseio.com/);
    返回$ firebaseAuth(REF);
  }
]);
app.controller(AuthCtrl,[$范围,验证,
  功能($范围,验证){
      $ scope.createUser =功能(){        $ scope.message = NULL;
        $ scope.error = NULL;
    VAR REF2 =新的火力地堡(HTTPS://unique$c$crs.firebaseio.com/);
  ref2.createUser({
    电子邮件:$ scope.email,
    密码:$ scope.password
  },功能(错误,用户数据){
    如果(错误){
      开关(误差。code){
        案EMAIL_TAKEN:
          警报(不能创建新的用户帐户,因为电子邮件是已在使用尝试登录。);
          打破;
        案INVALID_EMAIL:
          警报(指定的电子邮件是不是有效的电子邮件。);
          打破;
        案INVALID_PASSWORD:
          警报(以下简称指定Passowrd是无效的。)
          打破;
        默认:
          警报(创建用户时出错:错误);
      }
    }其他{
      警报(UID为成功创建用户帐户,userData.uid);
      警报($ scope.UserName)      window.location.hash =/用户
       $ scope.usernames =嗨
    }
  });
      };       $ scope.logIn =功能(){
        $ scope.message = NULL;
        $ scope.error = NULL;        ref2.authWithPassword({
          电子邮件:$ scope.logInemail,
          密码:$ scope.logInemailpassword        },功能(错误,用户数据){          如果(错误){
            警报(登录失败。)
            的console.log(错误)
          }
          其他{
            警报(登录!)
          }        })      }  / * $ scope.removeUser =功能(){
      $ scope.message = NULL;
      $ scope.error = NULL;      验证。$ removeUser({
        电子邮件:$ scope.email,
        密码:$ scope.password
      })。然后(函数(){
        $ scope.message =用户删除;
      })赶上(功能(错误){
        $ scope.error =错误;
      });
    }; * /
  }
]);


解决方案

有在code很多东西,你可能要照顾,但一些快速而肮脏的部分解决方案:

不包括所有的JavaScript文件在你的嵌套模板。被路由到您的 NG-查看任何应该只是你想成为内插入HTML &LT; D​​IV&GT; 。无CSS链接,没有脚本标签,不过HTML,通常会是一个网页的正文中。

在注册页面,您的用户名 NG-模型需要匹配您传递什么作为参数传递给你的 NG-点击。因此,而不是 NG-模式=username的你需要它是 NG-模式=用户名匹配 NG-点击=的createUser(用户名,电子邮件,密码)

您其他的主要问题是 $范围每次你改变看法,因为你的路由每个人都有相同的控制器时被覆盖。所以,从概念上讲,你可能会以为用户名(你所存储的复数 $ scope.usernames 对于一些原因)是有你访问仍 $范围。但事实并非如此,因为每个视图在验证控制器自己独特的实例中运行。因为你最快的解决办法不知道如何实现服务可能是注入 $ rootScope 到控制器中,然后把用户名 $ rootScope 而不是 $范围(但是请记住,使用 $ rootScope 在生产中被认为是不好的做法),为$ rootScope将在所有的控制器存在。所以,你的JavaScript文件看起来会是这样的:

app.controller(AuthCtrl,[$范围,$ rootScope,验证,
  功能($范围,$ rootScope,验证){

然后

$ scope.createUser =功能(用户名,电子邮件,密码){
        $ rootScope.usernames =用户名
        $ scope.message = NULL;
        $ scope.error = NULL;

Ok guys so 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 some reason... please help here is the plunkr:

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

Please i need help..

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:

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.

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)".

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

and then

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

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

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