Show loading animation for slowscript using AngularJS?

前端 未结 8 565
野的像风
野的像风 2020-12-24 12:08

In angularjs 1.2 operations like filtering an ng-repeat with many rows (>2,000 rows) can become quite slow (>1 sec).
I know I can optimize execution times u

8条回答
  •  长情又很酷
    2020-12-24 12:44

    Here is an working example :-

    angular
      .module("APP", [])
      .controller("myCtrl", function ($scope, $timeout) {
        var mc = this
        
        mc.loading = true
        mc.listRendered = []
        mc.listByCategory = []
        mc.categories = ["law", "science", "chemistry", "physics"]
        
        
        mc.filterByCategory = function (category) {
          mc.loading = true
          // This timeout will start on the next event loop so 
          // filterByCategory function will exit just triggering 
          // the show of Loading... status
    
          // When the function inside timeout is called, it will
          // filter and set the model values and when finished call 
          // an inbuilt $digest at the end.
          $timeout(function () {
            mc.listByCategory = mc.listFetched.filter(function (ele) {
              return ele.category === category          
            })
            mc.listRendered = mc.listByCategory
            $scope.$emit("loaded")
          }, 50)
        }
        
        // This timeout is replicating the data fetch from a server
        $timeout(function () {
          mc.listFetched = makeList()
          mc.listRendered = mc.listFetched
          mc.loading = false    
        }, 50)
        
        $scope.$on("loaded", function () { mc.loading = false })
      })
      
      function makeList() {
        var list = [
          {name: "book1", category: "law"},
          {name: "book2", category: "science"},
          {name: "book1", category: "chemistry"},
          {name: "book1", category: "physics"}      
        ]
        var bigList = []
        for (var i = 0; i <= 5000; i++) {
          bigList = bigList.concat(list)
        }
        return bigList
      }
    button {
      display: inline-block;      
    }
    
      
        This is an Angular Js Filter Workaround!!
      
       
      
        
        

    Loading...

    • {{ele.name}} - {{ele.category}}

提交回复
热议问题