Edgar Abgaryan Edgar Abgaryan - 2 months ago 16
AngularJS Question

controller Syntax with transclude

I'm trying to customize directuve 'angular-popover'.

<a angular-popover
direction="bottom"
template-url="assets/app/common/templates/popovers/page-choose.html"
class="content_paginator_trigger openPaginator inline-block pull-left">
<span class="content_paginator_trigger_text popoverTriger">
Page {{$ctrl.data.current_page}} of {{$ctrl.data.last_page || 1}}
</span>
</a>


That directive use inherit scope.

scope: true


$ctrl outside, inside and in the 'template-url' is the same.

If I change it on isolate scope then I'm loosing $ctrl context in template. Template is adding via ng-transclude attribute

scope: {
onOpen: "&onOpen"
}


How can I pass some function from $ctrl to 'angularPopover' directive?

Answer

You can create a service that gets called by both the controller and the directive.

(function (ng) {
  'use strict';

  ng.module('ServiceDemo')
    .service('DemoService', DemoService)
    .controller('DemoController', DemoController)
    .directive('DemoDirective', DemoDirective);

  function DemoService () {
    var self = this;

    self.onOpen = onOpen;

    function onOpen () {
      console.log('onOpen called!');
    }
  }

  function DemoController (DemoService) {
    var demoControllerVM = this;

    demoControllerVM.onOpen = DemoService.onOpen;
  }

  function DemoDirective (DemoService) {
    return {
      restrict: 'A',
      scope: {},
      templateUrl: 'path/to/directive/template.html',
      controllerAs: 'demoDirectiveVM',
      bindToController: true,
      controller: function ($scope, $element, $attrs) {
        var demoDirectiveVM = this;

        demoDirectiveVM.onOpen = DemoService.onOpen;
      }
    };
  }
})(angular);