0

I've came across with problem exposing api of directives in order to its interaction with controller.

There is a simplified jsfiddle to describe my structure.

The problem is that directives has templateUrl property (I replaced it with template in fiddle above), it leads to loading templates async (correct behavior according to this question).

As a result directive's controller is called after main controller therefore directive's api function doWork is undefined (even if you wrap it call with something like $timeout):

.controller('MainCtrl', function($scope, $timeout) {
    $scope.api = {};

    $scope.init = function() {
    $timeout(function() {
        $scope.api.doWork();
    })
  }

  $scope.init()
})

There is an approach that comes to my mind - use event in link function of directive and subscribe $scope.api.doWork to that event. But I'm not happy about using events. Also it's not clear how to handle such case if there are some directives nested to each other with similar way of exposing api. On the other hand it's possible to replace templateUrl with template - but it's also quite bad decision in case of complex layout in template.

Hence, I stuck a bit with the way to resolve such kind of problem. What's the best way to fix it out? Probably there is another technique to expose directive's api (I was inspired by Andrej Kaurin answer in that thread)?

Community
  • 1
  • 1
user1820686
  • 2,008
  • 5
  • 25
  • 44

1 Answers1

1

If you are using Angular 1.5+ and are using components you could try $postLink or $onInit function link. Otherwise you just create onDoWork directive scope property and then apply some function from main controller that will be fired when doWork will actually happen(since I think that directive should control when to doWork, if not then maybe you should just create service ?)

Maksym
  • 3,276
  • 3
  • 22
  • 27