为了简化...我需要读取子指令作为父指令中的数据我得到类似的东西:
<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
那么我如何创建另一个指令并在此链接函数中获取类似于头数组的内容?
答案 0 :(得分:2)
你实际上可以深入研究指令控制器和&#34; transclusions&#34;。
要访问父控制器,您可以使用require
选项。
.directive 'parent', ->
controller: ->
@addHeader = (header) => #do add header
.directive 'child', ->
require: '^parent'
link: (scope, el, attr, parent) ->
parent.addHeader 'from child'
但是你需要确保你的子链接功能实际运行。
例如(警告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>
答案 1 :(得分:0)
我能想到的唯一方法是在链接函数中使用element参数。您可以使用jqLite方法在ng-table指令中获取带有header标签的所有元素。
如果我更正,您无法从父作用域访问子作用域,因此使用jqlite可能是唯一的选择。见AngularJS - Access to child scope