Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Only Show View If Server Data Present

In my regular Javascript I append data to HTML ONLY if there's data from the server, otherwise I just show a simple div saying there's nothing. How can I implement this in AngularJS?

Example:

if (AJAXresult) 
    $element.append(JSONdata); //JSONdata will contain a list of customer data
else
    $element.append('<div>No results</div>');

How can I achieve this in Angular?

like image 528
user3704920 Avatar asked Jan 19 '26 17:01

user3704920


1 Answers

The simplest way would be to control for the no data state in your returned view.

<div>
   <div ng-if="!hasCustomers">
     No Customers Available
   </div>
   <div ng-if="hasCustomers">
     <!-- show some stuff -->
   </div>
</div>

Then in your controller you can easily initialize this when you load your data:

angular.module('myApp').controller('MyController', function($scope, myDataService){
    $scope.hasCustomers = false;

    myDataService.getCustomers()
    .then(function(value){
        $scope.customers = value.data;

        $scope.hasCustomers = customers && customers.length;        
    });
});

If you want to make sure the data is loaded before your view is ever instantiated, then you can also use the resolve property on your $route

$routeProvider.when('/someRoute/',{
   templateUrl: '/sometemplate.html',
   controller: 'MyController',
   controllerAs: 'ctrl', // <-- Highly recommend you do this
   resolve: {
      customerData: function(myDataService){
          return myDataService.getCustomers();
      }
   }
});

resolve is basically a hash of functions that return a promise, and can be dependency injected just like everything else. The controller and view will not be loaded until all the resolve promises have been fulfilled.

It will be available in your controller by the same property name you gave it:

angular.module('myApp')
.controller('MyController', function($scope, customerData){
   $scope.customers = customerData;
   $scope.hasCustomers = customerData && customerData.length;
});
like image 117
Josh Avatar answered Jan 22 '26 07:01

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!