user1732055
user1732055

Reputation: 2507

How to delay controller execution before service is done

I am trying to create an Angular service that runs before a controller is executed. I know I could use the 'resolve' properties of the controller but that makes me repeat that across all my controller.

So how can I create a service that uses some Ajax requests and have the controller wait for its execution?

Thanks

Upvotes: 2

Views: 2201

Answers (1)

winkerVSbecks
winkerVSbecks

Reputation: 1173

It's not possible to delay a controller however, you can ensure that a service is loaded before passing it to scope or refresh the scope when it changes. There are a few different ways to do this:

Create a variable in scope only if the service is loaded:

MyService.get({}, function(serv) {
  self.original = serv;
  $scope.serv = new MyService(self.original);
});

If you are using $http instead and wait for success to pass value to scope.

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // --- do your thing here ---
  }).
  error(function(data, status, headers, config) {

  });

Use $watch to see if a variable was updated or not:

scope.$watch('myVariableToWatch', function(value) {
   scope.myVariableToWatch = value;
})

Lastly you could also choose to hide any view elements until the service is loaded, so the HTML would be:

<div ng-show="serviceDidLoad"> some content here </div>

Put $scope.serviceDidLoad = true in the controller where you test to see the service has been loaded

Upvotes: 1

Related Questions