controller包含transclude的语法

时间:2016-09-26 17:14:01

标签: angularjs

我正在尝试定制directuve'angle-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>

该指令使用继承范围。

scope: true
外部,内部和'template-url'中的$ ctrl是相同的。

如果我在隔离范围上更改它,那么我在模板中丢失$ ctrl上下文。模板正在通过ng-transclude属性添加

scope: {
    onOpen: "&onOpen"
}

如何将$ ctrl中的某些函数传递给'angularPopover'指令?

1 个答案:

答案 0 :(得分:0)

您可以创建一个由控制器和指令调用的服务。

(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);