AngularJS 使用 child 指令作为指令数据

AngularJS Use child directives as directive data

简而言之...我需要阅读 child 指令作为 parent 指令中的数据 我得到了类似的东西:

<ng-table url="http://api.com/getArchive1" editUrl="http://api.com/editArchive1" etc>
 <header name="id" paramName="user_id"><header/>
 <header name="name" etc></header>
 <header name="age" etc></header>
</ng-table>

所以我得到了类似的东西(警告,COFFEESCRIPT :P):

table.directive 'ngTable', (Table) ->
  restrict    : "E"
  templateUrl : "table.html"
  link : (scope, element, attrs) ->
    scope.grid = new Table(attrs) //this is a class
    //other stuff

那么我如何创建另一个指令并在这个 link 函数中获取类似于 headers 的数组?

我能想到的唯一方法是在 link 函数中使用元素参数。您可以使用 jqLit​​e 方法来获取 ng-table 指令中带有 header 标记的所有元素。

如果我是对的,您无法从 parent 范围访问 child 范围,因此使用 jqlite 可能是唯一的选择。见 AngularJS - Access to child scope

您实际上可以深入研究指令控制器和 "transclusions"。

要访问 parent 控制器,您可以使用 require 选项。

.directive 'parent', ->
  controller: ->
    @addHeader = (header) => #do add header

.directive 'child', ->
  require: '^parent'
  link: (scope, el, attr, parent) ->
    parent.addHeader 'from child'

但您需要确保您的 child link 功能确实 运行。

例如(警告 JAVASCRIPT!!! :) 您可以使用 transclude 选项。 Sophisticated Example.

  .directive('myTable', function() {
    return {
      restrict: 'E',
      controller: function() {
        var headers = []
        this.headers = headers
        this.addHeader = headers.push.bind(headers)
      },
      template: `
        <table>
          <thead>
            <tr>
            </tr>
          </thead>
        </table>
      `,
      transclude: {
        // transclude all myHeaders into headers slot
        headers: 'myHeader' // transclude (how this is a real word at all?)
      },
      link: function(scope, el, attrs, ctrl, transclude) {
        var headerRow = el.find('thead').children('tr')

        // append all headers into thead wrapping with th
        transclude(function(headers) {
          [].forEach.call(headers, header => {
            var cell = angular.element('<th></th>')
            cell.append(header)
            headerRow.append(cell)
          })
        }, headerRow, 'headers')

        console.log(ctrl.headers) // headers were populated here
      }
    }
  })
  .directive('myHeader', function() {
    return {
      restrict: 'E',
      require: '^myTable',
      transclude: true, // ohh more transclusions
      template: '<span ng-transclude></span>', 
      link: function(scope, el, attrs, myTable) {
        myTable.addHeader(attrs.name) // report to myTable
      }
    }
  })

<my-table>
  <my-header name="First"> First Header </my-header>
  <my-header name="Second"> Second <span style="color:red;">Header</span> </my-header>
</my-table>