【问题标题】:AngularJS Controller submit formAngularJS 控制器提交表单
【发布时间】:2017-10-23 05:46:12
【问题描述】:

我的控制器有问题

 .factory('Auth', function($firebaseAuth){
  var auth = $firebaseAuth();
  return auth;
 })

.controller('authCtrl', function() {
  var authCtrl = this;

  authCtrl.user = {
    email: '',
    password: ''
  };

  console.log('hoi1');

  authCtrl.login = function (){
    console.log('hoi2');
  };
});

-

<div id="loginModal" class="modal" ng-controller="authCtrl">
<div class="modal-background"></div>
<div class="modal-content">
  <div class="modal-body">
    <form ng-submit="authCtrl.login()">
      <h1>Login</h1>
      <p id="loginError">&nbsp;</p>
      <input type="email" name="loginEmail" value="" placeholder="email" class="input" ng-model="authCtrl.user.email">
      <br>
      <input type="password" name="loginPassword" value="" placeholder="******" class="input" ng-model="password" ng-model="authCtrl.user.password">
      <br>
      <input type="submit" value="Login">
    </form>
  </div>
</div>

控制器一直在我体内,但是我在控制台看到hoi1,但是当我提交表单时,却没有得到hoi2

怎么了?

真诚地, 尤尔

【问题讨论】:

  • 试试ng-controller="authCtrl as authCtrl"。 @HARI 的答案有效,但不是最佳实践。

标签: angularjs firebase firebase-authentication angularfire


【解决方案1】:

改变

<div id="loginModal" class="modal" ng-controller="authCtrl"> 

<div id="loginModal" class="modal" 
ng-controller="authCtrl as authCtrl">

如果你想使用controller this 那么你必须将ng-controller 添加为ng-controller="authCtrl as authCtrl"

查看tutorial 了解有关 Controller as 的更多信息

Working Fiddle Example

【讨论】:

  • 谢谢,这个适用于我的选择。祝你有美好的一天。
【解决方案2】:

在你的控制器中使用 $scope

.controller('authCtrl', function( $scope) {
   $scope.user = {
      email: '',
      password: ''
   };

   console.log('hoi1');

   $scope.login = function (){
    console.log('hoi2');
   };
});

【讨论】:

  • $scope.login = function(){console.log('hoi');} &lt;form ng-submit="login()"&gt; 有效,但为什么它不适用于authCtrl
  • 您可以查看以下链接,其中简要解释了为什么stackoverflow.com/questions/11605917/…
【解决方案3】:

这是因为当您的 $scope 在控制器中执行以查看时,它会执行 console.log('hoi1') 因为它不等待任何事件发生。您只需编写“调试器;”在您的代码中并需要检查其执行部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多