You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS表单提交后未跳转问题排查请求

AngularJS 1登录跳转问题排查与修复

代码中的核心问题:

  • AngularJS应用未初始化:页面未添加ng-app="myApp"指令,导致AngularJS框架完全不生效,ng-model、ng-controller等所有指令都不会被解析。
  • 作用域层级错误:用户名、密码输入框位于LoginController作用域之外,$scope.username和$scope.password无法获取输入值,登录验证逻辑永远触发不了正确分支。
  • 表单与提交逻辑绑定错误:
    • ng-submit应绑定在<form>标签上,而非内部div;
    • 表单的name="myForm"属性错误放在div上,导致表单验证的myForm对象不存在;
    • 提交按钮的ng-click="function()"是无效代码,且未设置type="submit",点击时会触发浏览器默认表单提交行为(清空表单并刷新页面)。
  • 依赖注入缺失:控制器中使用$window但未在依赖注入列表声明,会导致$window未定义错误,无法执行跳转逻辑。

修正后的完整代码:

<head>
  <title>Authentication</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>

<body ng-app="myApp">
  <form name="myForm" ng-controller="LoginController" ng-submit="login()">
    <p>Username:<br>
      <input type="text" name="user" ng-model="username" placeholder="Enter user1" required>
      <span ng-show="myForm.user.$dirty && myForm.user.$invalid">
        <span ng-show="myForm.user.$error.required">Username is required.</span>
      </span>
    </p>
    <p>Password:<br>
      <input type="password" name="password" ng-model="password" placeholder="Enter secret123" required>
      <span ng-show="myForm.password.$dirty && myForm.password.$invalid">
        <span ng-show="myForm.password.$error.required">Password is required.</span>
      </span>
    </p>
    <button type="submit">Submit</button>
  </form>

  <script>
    const app = angular.module('myApp', []);

    app.controller('LoginController', function ($scope, $window) {
      $scope.login = function () {
        if ($scope.username === "user1" && $scope.password === "secret123") {
          $window.location.href = "./infoPage.html";
        } else {
          alert("Invalid username or password!");
        }
      };
    });
  </script>
</body>

关键修正点说明:

  1. 在<body>标签添加ng-app="myApp",启动AngularJS应用;
  2. 将ng-controller="LoginController"、name="myForm"、ng-submit="login()"全部移到<form>标签上,确保所有表单元素处于控制器作用域内,同时正确绑定提交逻辑;
  3. 移除提交按钮的无效ng-click,添加type="submit",确保点击时触发ng-submit绑定的login()函数;
  4. 在控制器依赖注入中添加$window,确保可以正常使用其跳转方法。

内容的提问来源于stack exchange,提问作者Robert Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:12:35