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?

4

1 回答 1

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>
于 2013-09-14T14:55:04.110 回答