AngularJS 控制器提交表单

AngularJS Controller submit form

我的控制器有问题

 .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

怎么了?

真诚的, 周

在控制器中使用 $scope

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

   console.log('hoi1');

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

这是因为当你的 $scope 在控制器中执行查看时,它执行 console.log('hoi1') 因为它不等待任何事件发生。你只要在你的代码里写"debugger;",需要检查它的执行部分

改变

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

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

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

查看此 tutorial 以获取有关 Controller 的更多信息

Working Fiddle Example