Search code examples
javascriptangularjsjsonsmartyloading

"loading" or "wait" message before my JSON data loads in AngularJS


I have seen some solutions on how to put a wait msg before the JSON data gets loaded from a URL or a separate file using $http get() request but I haven't seen with JSON with a smarty format in the HTML file itself. In this case {$data} is my JSON array that looks like this {"title":"A2378","sub_name":"A2333", .....}. Any easy way on how to put a wait msg before my json gets loaded on my html file?

<script type="text/javascript">
var app= angular.module('mysearch', []);
app.controller('mysearchController', ['$scope', function($scope){
        $scope.products = {$data}; 
]);
</script>

<div ng-app="mysearch">
   <div ng-controller="mysearchController">
      <div ng-repeat="item in products">
           {{item.sub_name}}
      </div>
      <p> {{item.title}}</p>
   </div>
</div>

Thanks in advance!


Solution

  • Just set a flag in your scope to indicate whether you have loaded the data:

    <div ng-app="mysearch">
       <div ng-controller="mysearchController">
          <div ng-if="!loaded">Loading...</div>
          <div ng-if="loaded">
            <div ng-repeat="item in products">
               {{item.sub_name}}
               <p> {{item.title}}</p>
            </div>
          </div>
       </div>
    </div>
    

    Then your controller can set that flag true when you have finished loading the data. e.g.:

    app.controller('mysearchController', ['$scope', function($scope){
        $scope.loaded = false;
        $http.get('...').then(function(response) {
             $scope.products = response.data;
             $scope.loaded = true;
        });
    ]);
    

    Obviously if you are loading the data by some other mechanism your code won't look exactly like this, but the idea is the same, just toggle a flag when the data is completely loaded.