2016-09-20 147 views
0

我想在JS做某事時顯示用戶加載gif。頁面加載時加載gif

在我開始之前,我想說我發現了多篇關於這個主題的文章,但沒有人能幫助我。

  • 我發現使用攔截器倍數(例如thisthis
  • 也發現了一些與單個控制器/指令(如this

我想要什麼: 我想作更復雜的東西。因此,任何控制器或任何指令都可以訪問以更改加載狀態並顯示它。

什麼我嘗試:

我開始製作LoadingService授予訪問權限從任何地方更改狀態:

myApp.service('LoadingService', ['$timeout', function($timeout) { 
     var loading = false; 

     this.isLoading = function() { 
      return loading; 
     }; 

     this.stopLoading = function() { 
      // loading will be visible at least 1s 
      $timeout(function() { 
       loading = false; 
       console.log(loading); 
      }, 1000); 
     }; 

     this.startLoading = function() { 
      loading = true; 
      console.log(loading); 
     } 
}]); 

之後,我創建一個HeaderCtrl,我想顯示加載GIF默認情況下:

myApp.controller('headerCtrl', ['$scope', 'LoadingService', function ($scope, LoadingService) { 
    $scope.isLoading = LoadingService.isLoading(); 
}]); 

然後在我的其他控制器我嘗試啓動和停止

LoadingService.startLoading(); 
// Some code between 
LoadingService.stopLoading(); 

什麼actualy發生:

沒什麼,更具體,裝載值從false變爲true然後回到false但圖像沒有顯示。

例子: 我知道這可能是非常複雜的問題,所以我創造出可以在這裏找到一個活生生的例子:http://plnkr.co/edit/43HdyLBB9ri0s6yQbJ8X?p=preview

感謝您的任何建議。

+0

'LoadingService.isLoading();'它只是在那一刻返回變量的值,當變量以後更新會出現無人繼承 – charlietfl

回答

0

不是將isLoading的值設置爲scope.isLoading,而是設置函數本身。然後在模板中調用它。

Example

myApp.directive("loader", ['LoadingService', function(LoadingService) { 
    return { 
     restrict: "E", 
     // templateUrl: 'src/templates/loader.html', 
     template: '<div ng-if="isLoading()">LOADER</div>', 
     link: function(scope) { 
      scope.isLoading = LoadingService.isLoading; 
     } 
    } 
當你調用