我正在尝试创建一个按钮,该按钮可以对其正在执行的操作提供反馈。在Angular中,我正在向服务器发出put请求 - 此时我更改按钮的状态以指示这一点 - 然后当我收到响应时,我再次更改按钮的状态以反映1.5秒的成功或失败,然后重置它回到单击按钮之前的原始状态。此时,还会显示一条消息以反映成功或失败,并在另外5秒后执行其他操作。如果失败则显示的消息应该被隐藏,如果成功则页面应该重定向。这是我不能开始工作的最后一部分。
因此,我的问题是我是否应该将setTimeout放入另一个setTimeout?
这是我的代码(在按钮的功能内):
$scope.resetPassword = function() {
$scope.ShowSuccessMessage = false;
$scope.ShowFailedMessage = false;
var querystring = $location.search();
var dataObject = { email1 : $scope.formEmail1, email2 : $scope.formEmail2, password1: $scope.formPassword1, password2: $scope.formPassword2, token: querystring.token };
var responsePromise = $http.put("/myurl/", dataObject, {});
// change colour and icon of reset button for 1.5 sec
var $el = $("#resetPassword");
var resetButton = 1500;
var resetMessage = 5000;
var originalColor = $el.css("background");
var originalIcon = $el[0].firstChild.className; // get first html element in the button, which is the <i>
$el[0].firstChild.className = "fa fa-circle-o-notch fa-spin";
responsePromise.success(function(dataFromServer, status, headers, config) {
$el.css("background", "#02c66c");
$el[0].firstChild.className = "fa fa-check-circle";
$scope.ShowSuccessMessage = true;
ResetButton($el, $scope, originalColor, originalIcon, resetButton, true, resetMessage);
});
responsePromise.error(function(dataFromServer, status, headers, config) {
$el.css("background", "#d9534f");
$el[0].firstChild.className = "fa fa-times-circle";
$scope.ShowFailedMessage = true;
ResetButton($el, $scope, originalColor, originalIcon, resetButton, false, resetMessage);
});
};
ResetButton = function(el, scope, originalColor, originalIcon, resetButton, success, resetMessage)
{
setTimeout(function() {
el.css("background", originalColor);
el[0].firstChild.className = originalIcon;
ChangeMessageOrChangeLocation(scope, success, resetMessage);
}, resetButton);
}
ChangeMessageOrChangeLocation = function(scope, success, resetMessage)
{
if(success) {
setTimeout(function(){
window.location = '/signin';
}, resetMessage);
}
else {
setTimeout(function() {
scope.ShowFailedMessage = false;
}, resetMessage);
}
}
编辑:这是一个实例:Greedy Magpie(请记住,这是一项正在进行的工作,因此网站上的所有内容都不会有效。)只需点击更改密码按钮即可...
答案 0 :(得分:1)
winfow.setTimeout在Angular摘要周期之外执行,因此视图未更新。在scope.$apply()
之后添加scope.ShowFailedMessage = false;
或使用$timeout
服务而不是setTimeout。第二种方法更好。
点击此处查看$ timeout服务文档:$timeout