Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Resolving not in RouteProvider but in Controller?

I saw some sample code here Delaying AngularJS route change until model loaded to prevent flicker

And straight away I though this was the right way to go, I need to have my controller LOAD only when a resolve is finished loading, normally most of the examples around tell you to put the code under resolve in the routeprovder as an inline function, but this sounds wrong. The controller needs it so why not have the controller implement the function to resolve. This sounded just what I was looking for ie. This seems to use the prototype pattern ??

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {
  phones: function(Phone, $q) {
    // see: https://groups.google.com/forum/?fromgroups=#!topic/angular/DGf7yyD4Oc4
    var deferred = $q.defer();
    Phone.query(function(successData) {
            deferred.resolve(successData); 
    }, function(errorData) {
            deferred.reject(); // you could optionally pass error data here
    });
    return deferred.promise;
  }
}

Problem is I have my controller like so

'use strict';

angular.module('TestApp')
  .controller('ItemsCtrl', function ($scope) {
});

So how do I apply a new function on the controller when my controller is declared inside a module ?

What I really need is something like

 TestCtrl.resolve = {
      items: function( $q) {
          ..........
        return deferred.promise;
      }
    }

This then would allow me to have in my routeprovider..

  when('/items', {
    templateUrl: 'views/items.html', 
    controller: 'TestCtrl', 
    resolve: 'TestCtrl.resolve'}). // Need to use ' around resolve?

But I am confused how I would get this to work ?

I would really love any feedback, I am at a loss.

like image 353
Martin Avatar asked Dec 20 '22 02:12

Martin


2 Answers

Not possible to define like 'TestCtrl.resolve' if you want to use resolve with .controller syntax then you have to define inline within route provider . The advantage of inline resolve in routeprovider is that you can reuse controller easily but using same controller and changing the logic in resolve function

like image 80
Ajay Beniwal Avatar answered Dec 31 '22 14:12

Ajay Beniwal


You can also use a service:

resolve: {data : function(service) {
  return service.getData();
}}
like image 29
Narretz Avatar answered Dec 31 '22 15:12

Narretz