2014-10-30 45 views
1

在AngularJS(真棒框架!)中創建我的應用程序時,我陷入了一個任務:在某些操作後如何顯示和隱藏隱藏的divng-show)。AngularJS在延遲後隱藏div

詳細描述:使用AngularUI $modal服務我問,如果用戶想執行操作,如果是,我運行服務通過$http爲POST請求發送我想刪除哪個項目。完成後,我想用信息顯示隱藏的div,該過程已成功完成。我創建了一個簡單的服務$timeout設置div'sng-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 
}; 

與$超時簡單服務後改變布爾值一段時間

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

更改showAlertSrvc服務的實現,像這樣:

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

,然後改變THES 2線:

deleteSuccessInfo聲明應該是這樣的:

$scope.deleteSuccessInfo = {}; 

而且然後執行此操作:

$scope.deleteSuccessInfo = showAlertSrvc(4000); 

最後,在你看來這樣做"ng-show=!deleteSuccessInfo.hidden"

Example

+0

謝謝你的解決方案何塞普。無論如何,我希望創建一個可重用的showAlertSrvc服務,我可以使用其他控制器(如創建項目)輕鬆使用。 – cachaito 2014-10-30 23:06:17

+0

@cachaito我會更新我的答案,以解釋爲什麼這項服務不值得,請在5分鐘內查看我的答案。沒有這項服務有一個很好的理由。 – Josep 2014-10-30 23:07:50

+0

我會等待@Josep :-)與此同時,我讀了$ q docs,並在retunredPromise.then(successCallback,errorCallback,notifyCallback)中發現了第三個回調函數。你會說什麼來設置:$ scope.deleteSuccessInfo = true在successCallback並設置$超時與$ scope.deleteSuccessInfo = false在notifyCallback? – cachaito 2014-10-30 23:22:02