[英]Display an alert after submitting a form using angularjs
我正在使用AngularJS作為登錄表單,我正在使用用戶名/密碼對服務器進行API調用並顯示警報。
login.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-success
, alert-warning
),但它會立即顯示警報,而不會消失。 如果我刪除$scope.alert = data.alert
,一切正常。 我正在考慮擁有2/3 div.alert
,並且具有不同的范圍( $scope.alert1
, $scope.alert2
),但我確信有更好的方法。
此外,在初始加載時,顯示div.alert
然后淡出。 我可以設置display: none
警報display: none
加載時display: none
,但我正在尋找一種“更清潔”的方式。
英語不是我的母語,所以我可能犯了錯誤,道歉。 謝謝。
$scope.showAlert = true
超出了您的success
和error
回調。 因此,只要您將呼叫設置為$http
,就可以將showAlert
設置為true
。
請記住, $http
服務返回一個promise,並且不會立即調用回調(在這種情況下success
和error
)。 只有在服務器響應后才會調用它們。 嘗試在您的成功函數中設置$scope.showAlert = true
,看看它是否更像您期望的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.