javascript - AngularJS Only Show View If Server Data Present - Stack Overflow

In my regular Javascript I append data to HTML ONLY if there's data from the server, otherwise I j

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?

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?

Share Improve this question asked Jun 20, 2014 at 19:43 user3704920user3704920 6151 gold badge8 silver badges19 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

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 remend 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;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745631358a4637129.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信