using ng-show with the length of the array after calling the Web service

advertisements

I am trying to show an alert box if the size of an array is 0. The array is populated by a web service call and is thus 0 when the controller loads. When the promise is resolved the array is populated, but the alert stays on the page.

How can I update the view state of alert after the promise has completed? Here is what I have so far:

<div class="alert alert-danger" ng-show="!items.length">You have no items.</div>

profile.controller('myController', ['$scope', '$http', '$window',
  function($scope, $http, $window) {

    $http.get('/api/getItems').success(function(data) {
      $scope.items = data;
    });
  }
]);

here is the response:

[{"test" : "data"}]

When I try to use the apply function I get an inprogress error:

Error: [$rootScope:inprog] http://errors.angularjs.org/1.2.18/$rootScope/inprog?p0=%24digest

$http.get('/api/getItems').success(function(data) {
  $scope.$apply(function () {
    $scope.items = data;
  });
});

I ended up just hardcoding the items array when the controller loads... the div still shows up.


Unless you have code that isn't being shown here, there is no need for $timeout() or $scope.$apply().

After the $http.get() promise is resolved, the $scope.items value is populated and Angular runs a $digest cycle to update the view which will show/hide the alert based on the latest value of the expression (items.length).

This plunkr demonstrates different types of results and the view updates correctly. You can change the .json files to produce empty arrays and you will see the alert correctly show/hide.