1
function armyController($scope, $http) {
  var no_errors = true;
  function getArmyData () {
    $http
      .get('/army')
      .success(function(data) {
        $scope.army = data;
        getArmyData();
      })
      .error(function(data) {
        console.log('Error: ' + data);
        no_errors = false;
      });
  }
  if (no_errors) {
    getArmyData();
  }
}

This controller works but it is kind of ugly. How should I keep the $scope updated in a less hacky more efficient way?

Elemenofi
  • 374
  • 5
  • 18
  • The way i see it, is i try not to have the `$http` service in controllers, as it probably means that i need to make a provider to handle the transaction. This way segregate you http logic into maintainable modules, and don't clutter you controller with functions and variable that don't really need to know about each other. – Matthew.Lothian Jun 02 '14 at 03:54

2 Answers2

3

You should be using a service to encapsulate the service calls and maintain the data that you want to be persistent between various controllers. Your controllers will generally end up being much simpler this way see an example I wrote up here Angular $http vs service vs ngResource

Community
  • 1
  • 1
shaunhusain
  • 19,630
  • 4
  • 38
  • 51
1

You shouldn't use $http in controller that's number one rule. Could you explain more about no_errors, why you use like that, here is code after i refactor

function armyController($scope, $http, Army) {
  var no_errors = true;

  function getArmyData() {
     Army.get().then(function(data) {
       $scope.army = data;
       getArmyData();
     }, function() {
       console.log('Error: ' + data);
       no_errors = false;
     })
  }
  if (no_errors) {
    getArmyData();
  }
}

Arm is angularjs factory which you define that $http or $resource
MQuy
  • 39
  • 4
  • 11