AngularJS在延迟后隐藏div

时间:2014-10-30 22:48:45

标签: angularjs modal-dialog timeout q

在AngularJS中创建我的应用程序时(真棒框架!)我坚持一项任务:如何在某些操作后显示和隐藏隐藏的divng-show)。

详细说明:使用AngularUI $modal服务我问用户是否想要执行操作,如果是,我通过$http运行POST请求发送哪个我要删除的项目。完成后我想显示隐藏的div信息,该过程已成功完成。我使用$timeout创建了一个简单的服务来设置div's ng-show并在一段时间后隐藏,但它不会更新分配给ng-show指令的变量。这是一些代码:

列出和删除项目的控制器

 $scope.deleteSuccessInfo = false; //variable attached to div ng-show

 $scope.deleteCluster = function(modalType, clusterToDelete) {

    modalDialogSrvc.displayDialog(modalType)
        .then(function(confirmed) {

            if(!confirmed) {
                return;
            }

            clusterDeleteSrvc.performDelete(itemToDelete)
                .then(function(value) {
                    //my attempt to show and hide div with ng-show
                    $scope.deleteSuccessInfo = showAlertSrvc(4000);
                    updateView(itemToDelete.itemIndex);
                }, function(reason) {
                    console.log('Error 2', reason);
                });

        }, function() {
            console.info('Modal dismissed at: ' + new Date());
        });
};

function updateView(item) {
   return $scope.listItems.items.splice(item, 1);
}

删除项目的部分服务

function performDelete(itemToDelete) {

    var deferred = $q.defer(),
        path = globals.itemsListAPI + '/' + itemToDelete.itemId;

    getDataSrvc.makeDeleteRequest(path)
        .then(function() {
            console.log('Item removed successfully');
            deferred.resolve({finishedDeleting: true});
        }, function(reason) {
            console.log('error ', reason);
            deferred.reject(reason);
        });

    return deferred.promise;
}

return {
    performDelete: performDelete
};

使用$ timeout进行简单服务以在一段时间后更改布尔值

angular.module('myApp')
    .service('showAlertSrvc', ['$timeout', function($timeout) {

        return function(delay) {

            $timeout(function() {
                return false;
            }, delay);

            return true;
        };

    }]);

我尝试$scope.$watch('deleteSuccessInfo', function(a, b) {...})没有效果。一段时间后如何申请虚假?或者你可能会以其他方式实现这一目标吗?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

更改showAlertSrvc服务的实施,如下所示:

angular.module('myApp')
 .service('showAlertSrvc', ['$timeout', function($timeout) {
        return function(delay) {
            var result = {hidden:true};
            $timeout(function() {
                result.hidden=false;
            }, delay);
            return result;
        };
    }]);

然后改变2行:

deleteSuccessInfo的声明应该是这样的:

 $scope.deleteSuccessInfo = {}; 

然后这样做:

$scope.deleteSuccessInfo = showAlertSrvc(4000);

最后,在您的视图中执行此操作"ng-show=!deleteSuccessInfo.hidden"

Example