gpt4 book ai didi

javascript - 使用 angularjs 提交表单后显示警报

转载 作者:行者123 更新时间:2023-12-02 18:25:31 25 4
gpt4 key购买 nike

我使用 AngularJS 作为登录表单,并使用用户名/密码对服务器进行 API 调用并显示警报。

登录.jade

// form
input(type="submit",ng-click="submit()")
div.alert(ng-show="showAlert",class="{{alert}}",ng-animate="{show: 'alert-show', hide: 'alert-hide'}")
button(ng-click="showAlert = !showAlert") fadeIn

controller.js

$scope.submit = function () {
if ($scope.username != undefined && $scope.password != undefined) {
$http({
method: 'POST',
data: {
username: $scope.username,
password: $scope.password
},
url: 'api/login'
}).
success(function (data, status, headers, config) {
if (data.auth) {
$scope.alert = data.alert;
} else {
$scope.alert = data.alert;
}
}).
error(function (data, status, headers, config) {
// something else
});
$scope.showAlert = true;
}
}

data.alert 是警报的类(alert-successalert-warning),但它会立即显示警报,不褪色。如果我删除 $scope.alert = data.alert,一切正常。我正在考虑拥有 2/3 div.alert,并拥有不同的范围($scope.alert1$scope.alert2),但我我确信有更好的方法。

此外,在初始加载时,div.alert 显示然后消失。我可以在加载时在 display: none 上设置警报,但我一直在寻找一种“更干净”的方式。

英语不是我的母语,所以我可能犯了错误,我很抱歉。谢谢。

最佳答案

$scope.showAlert = true 位于 successerror 回调之外。因此,一旦您设置对 $http 的调用,您实际上就将 showAlert 设置为 true

请记住,$http 服务返回一个 Promise,并且不会立即调用回调(在本例中为 successerror)。仅当服务器响应时才会调用它们。尝试在 success 函数中设置 $scope.showAlert = true ,看看这是否更像您所期望的。

关于javascript - 使用 angularjs 提交表单后显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com