2017-01-09 124 views
0

我在路由和控制器上应用了一个教程。 问题是没有错误,但表单不提交变量到控制器!AngularJs表单提交不起作用

我尝试了另一种方式来提交表单,如提交类型的按钮,但它没有奏效。

controller.js:

var app = angular.module('mainApp', ['ngRoute']); 

    // configure our routes 
    app.config(function($routeProvider) { 
     $routeProvider 

      // route for the home page 
      .when('/', { 
       templateUrl : 'login.html' 
      }) 

      .when('/dashboard', { 
       templateUrl : 'dashboard.html' 
      }); 
    }); 

app.controller('loginCtrl',function($scope,$location){ 
console.log('login controller'); 
    $scope.submit = function(){ 
     var uname = $scope.username; 
     var pass = $scope.password; 
     console.log($scope.username); 

     if($scope.username == 'Admin' && $scope.password == '123456'){ 
      console.log('=='); 
      $location.path('/dashboard'); 
     } 
     else{ alert('Wrong stuff') 
    console.log('Error');}  
    };  
}); 

这里是html页面:

的index.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 

    <title>AJS</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.js"></script> 
<script src="controller.js"></script> 

</head> 
<body ng-app="mainApp"> 
    <div ng-view></div> 
</body> 
</html> 

这里是login.html的:

<div ng-controller="loginCtrl" > 
    <form id="loginForm" action="/" > 
    <table border="0"> 
     <tr> 
      <td> User Name:</td> 
      <td> <input type="text" name="username" id="username"></td> 
     </tr> 
    <tr> 
     <td>Password:</td> 
     <td><input type="password" name="password" id="password"></td> 
    </tr> 

    <tr> 
     <td></td> 
     <td><button type="button" ng-click="submit()" > Login </button></td>  
    </tr> 
    </table> 
    </form> 
</div> 
+1

你没有绑定您的输入型到你的控制器,以便$ scope.username和$ scope.password将是不确定的。在输入类型中使用ng-model =“username”属性 – anand

回答

2

您错过了ng-model指令在你的输入,输入值绑定到一个属性上的$范围

<div ng-controller="loginCtrl" > 
    <form id="loginForm" action="/" > 
    <table border="0"> 
     <tr> 
      <td> User Name:</td> 
      <td> <input ng-model="username" type="text" name="username" id="username"></td> 
     </tr> 
    <tr> 
     <td>Password:</td> 
     <td><input ng-model="password" type="password" name="password" id="password"></td> 
    </tr> 

    <tr> 
     <td></td> 
     <td><button type="button" ng-click="submit()" > Login </button></td>  
    </tr> 
    </table> 
    </form> 
</div>