1

I would like to have a directive which behaves as typical ng-controller, but I want it to be called once a promise is resolved, not sooner. In HTML this could be written like this:

<div ng-controller="myCtrl" ctrl-promise="p">

p could be any promise on parent scope. I know there is a way to delay instantiation of a controller for a route(as answered here: Angular.js delaying controller initialization), but I would much prefer to specify this per controller rather than per route. I know I could use ng-if with p as atribute, but is there other way?

Community
  • 1
  • 1
Capaj
  • 4,024
  • 2
  • 43
  • 56

1 Answers1

2

So you want the stuff inside the div to exist, just without the controller controlling it, until the promise is resolved?

Here is a directive which will create a controller when a promise is resolved:

angular.module('myApp')
.directive('delayController', function($controller, $q) {
  return {
    scope: true,
    link: function(scope, elm, attr) {
      $q.when(scope.$parent.$eval(attr.delayControllerPromise)).then(function() {
        var ctrl = $controller(attr.delayController, {
          $scope: scope
        });
        elm.children().data('$ngControllerController', ctrl);
      });
    }
  };
});

You can use it like this:

<div delay-controller="MyCtrl" delay-controller-promise="myPromiseExpr()">
</div>
Andrew Joslin
  • 43,033
  • 21
  • 100
  • 75
  • This works when I have my controller function on parent scope, but when I have it defined with regular angular.module('app', []).controller('myCtrl', ...) it obviously won't inject it there. I have tried injecting it by calling $injector.get(attr.delayController) but that just returns an error: Unknown provider: MyCtrlProvider <- MyCtrl, why isn't it injecting as it should? – Capaj Sep 14 '13 at 15:36
  • I should have read docs http://docs.angularjs.org/api/ng.$controller before I thought that it requires a function. Thanks for sticking around! – Capaj Sep 14 '13 at 16:13
  • I have trouble with scope.$eval(attr.delayControllerPromise). In the plnkr it resolves to undefined instead of the promise object, so the controller is not delayed at all. Why?? I even tried creating a parent controller where I stored the promise too, but no luck... – Capaj Sep 14 '13 at 16:30
  • Try scope.$parent.$eval - since the directive creates a child scope. – Andrew Joslin Sep 14 '13 at 17:06