</>
Skip to content
AngularJS lessons (20/28)

AngularJS — AJAX

Loading Data

app.controller('DataController', function($scope, $http) {
  $scope.loading = true;
  
  $http.get('/api/data')
    .then(function(response) {
      $scope.data = response.data;
      $scope.loading = false;
    })
    .catch(function(error) {
      $scope.error = 'Failed to load data';
      $scope.loading = false;
    });
});

Template with Loading

<div ng-controller="DataController">
  <div ng-show="loading">Loading...</div>
  <div ng-show="error">{{error}}</div>
  <div ng-hide="loading || error">
    <ul>
      <li ng-repeat="item in data">{{item.name}}</li>
    </ul>
  </div>
</div>

Error Handling

$scope.handleError = function(error) {
  if (error.status === 401) {
    $location.path('/login');
  } else if (error.status === 404) {
    $scope.message = 'Not found';
  } else {
    $scope.message = 'Server error';
  }
};

Caching

app.factory('CacheService', function($cacheFactory) {
  return $cacheFactory('myCache');
});

// In controller
$http.get('/api/data', { cache: CacheService });

Mini Practice

  1. Load data with AJAX
  2. Show loading state
  3. Handle errors
  4. Implement caching

Up Next

Continue with Routing — AngularJS routing.

Related Topics

Frequently Asked Questions about AJAX

What is AJAX in AngularJS?

AJAX is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn AJAX?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn AJAX.

Why is AJAX important in AngularJS?

AJAX is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.