Angular登录表单if-else语句失效问题求助
问题修复方案
你的代码存在几个关键错误,直接导致功能失效,以下是逐个修复说明及完整修正代码:
核心错误点
- 赋值/相等运算符混淆:判断条件里误用赋值符
=,而非相等判断符===/==,导致逻辑完全错误 - 变量名大小写不匹配:HTML中手机号绑定的是
phoneNumber(驼峰式),但JS判断时写成了phonenumber(全小写),无法正确读取值 - 表单默认提交行为:
submit按钮点击后会触发页面刷新,丢失Angular状态
修复后的完整代码
HTML部分
<body ng-app="myApplication" ng-controller="myController" ng-cloak> <h3>Contact Us</h3> <div id="showDiv" ng-show="firstPage"> <form> <label for="name">Name:</label> <input type="text" placeholder="Enter your name" ng-model="name"><br> <label for="email">Email:</label> <input type="email" placeholder="Enter your email" ng-model="email"><br> <label for="number">Number:</label> <input type="number" placeholder="Enter your number" ng-model="phoneNumber"><br> <label for="issue">Issue:</label> <textarea name="issue" rows="5" cols="20" placeholder="Enter your issue" ng-model="issue"></textarea> <br> <br> <!-- 改用button阻止默认表单提交,避免页面刷新 --> <button type="button" id="submit" ng-click="showHide()">Submit</button> <input type="reset" value="Reset" id="reset"> </form> </div> <div id="hideDiv" ng-show="secondPage"> <p ng-bind="feedback"></p> <p>Your contact details are:</p> <p>Email: <span ng-bind='email'></span></p> <p>Phone Number: <span ng-bind='phoneNumber'></span></p> <p>Your issue is:</p> <p><span ng-bind='issue'></span></p> <button type="button" id="goBack" ng-click="hideShow()">Go Back</button> </div> </body>
JavaScript部分
<script> angular.module('myApplication', []).controller('myController', function($scope){ $scope.name = ""; $scope.email = ""; $scope.phoneNumber = ""; $scope.issue = ""; $scope.firstPage = true; $scope.secondPage = false; $scope.showHide = function() { $scope.firstPage = false; $scope.secondPage = true; $scope.feedback = ""; // 修复:用===严格相等判断,修正变量名大小写 if ($scope.name === "Po Lu" && $scope.email === "Po.Tom@acc.ac.au" && $scope.phoneNumber === "021") { $scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ; } else if ($scope.name === "Mel Tom" && $scope.email === "Mel.Tom@acc.ac.au" && $scope.phoneNumber === "0217") { $scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ; } else { $scope.firstPage = true; $scope.secondPage = false; alert("Please Enter valid details"); } } $scope.hideShow = function() { $scope.firstPage = true; $scope.secondPage = false; $scope.name = ""; $scope.email = ""; $scope.phoneNumber = ""; $scope.issue = ""; } }); </script>
额外优化提示
- 优先使用
===严格相等判断,避免类型转换引发的意外问题 - 手机号输入为
type="number"时,值会转为数字类型,若需匹配字符串格式(如"021"),可将input的type改为text,或把判断值改为数字(如21) - 可将验证逻辑抽为独立函数,提升代码可读性
内容的提问来源于stack exchange,提问作者LizzyZao
相关产品推荐
相关产品推荐

