我有一个简单的场景
<thead grid-columns pager-info="pagerInfo" onsort="onSort()">
<tr>
<th width="15%"><column sortby='FName'>Name</column></th>
<th width="17%"><column sortby='Mobile'>Number</column></th>
</tr>
</thead>
我的想法是,由于我的所有列都需要定义onsort
,因此我可以在父级上定义一次。
但是,为什么我的child指令(列)没有将$parent
设置为grid-columns指令?相反,scope.$parent
设置为控制器范围,因此我无法弄清楚如何从我的子指令访问我的父指令范围。
这两个指令都有一个独立的范围,我的子指令转换为:
ngApp.directive('gridColumns', function () {
// Attribute-based wrapper round the columns that allows us to capture the pagerInfo and set a sort handler.
return {
restrict: 'A',
scope: {
pagerInfo: '=',
onsort: '='
}
};
});
ngApp.directive('column', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
sortby: '@'
},
template: "<span><a ng-click='sort()' ... </span>",
link: function (scope, el, attrs) {
scope.sort = function () {
// I want to call scope.$parent.onsort, but scope.$parent is the controller !
// scope.$parent.onsort(scope.sortby);
};
}
};
});
答案 0 :(得分:1)
您可以尝试require
:
ngApp.directive('column', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
sortby: '@'
},
template: "<span><a ng-click='sort()' ... </span>",
require:"^gridColumns",
link: function (scope, el, attrs,gridColumnsController) {//inject gridColumnsController
scope.sort = function () {
gridColumnsController.onsort(scope.sortby);//call the controller's onsort function.
};
}
};
});
更新您的gridColumns
以公开onsort
:
ngApp.directive('gridColumns', function () {
return {
restrict: 'A',
scope: {
pagerInfo: '=',
onsort: '&' //also update the function binding
},
controller:function($scope){
this.onsort = function (sortBy){
$scope.onsort({param:sortBy});
}
}
};
});
您的HTML:
<thead grid-columns pager-info="pagerInfo" onsort="onSort(param)">
您可以在此处获得更多信息:AngularJS - $emit only works within it's current scope?