我使用树网格插件(来自此链接:https://github.com/khan4019/tree-grid-directive)
我自定义了它的模板:
.directive('treeGrid', [
'$timeout', function($timeout) {
return {
restrict: 'E',
template:
"<div class=\"table-responsive\">\
<table id=\"policies\" class=\"table table-striped\">\
<colgroup>\
<col width=\"10%\" />\
<col width=\"70%\" />\
<col width=\"1%\" />\
<col width=\"1%\" />\
</colgroup>\
<thead>\
<tr>\
<th>Category</th>\
<th>Content</th>\
<th></th>\
<th></th>\
<th></th>\
</tr>\
</thead>\
<tbody>\
<tr ng-repeat=\"row in tree_rows | filter:{visible:true} track by row.branch.uid\" ng-class=\"'level-' + {{ row.level }} + (row.branch.selected ? ' active':'')\">\
<td class=\"text-primary\"><a ng-click=\"user_clicks_branch(row.branch)\"><i ng-class=\"row.tree_icon\"ng-click=\"row.branch.expanded = !row.branch.expanded\"class=\"indented tree-icon\"></i></a>\
<span class=\"indented tree-label\" ng-click=\"user_clicks_branch(row.branch)\"> {{row.branch[expandingProperty]}}</span></td>\
<td ng-bind-html=\"row.branch[colDefinitions[2].field]\"></td>\
<td> <a href=\"javascript:void(0)\" ng-click=\"editContent(row.branch)\" data-toggle=\"modal\" data-target=\"#new-content\" class=\"action\"><i class=\"glyphicon glyphicon-edit\"></i></a> </td>\
<td> <a ng-click=\"deleteContent(row.branch.Id)\" class=\"action\"><i class=\"glyphicon glyphicon-remove-circle\"></i></a> </td>\
</tr>\
</tbody>\
</table>\
</div>",
replace: true,
scope: {
treeData: '=',
colDefs:'=',
expandOn:'=',
onSelect: '&',
deleteContent: '&',
editContent: '&',
initialSelection: '@',
treeControl: '='
},
这样的 Controller :
.controller('ContentCtrl', ['$http', '$scope', '$location', '$localStorage', 'authService', 'settings', function ($http, $scope, $location, $localStorage, authService, settings) {
$scope.deleteContent = function(){
console.log("delete");
};
}]);
并查看:
<tree-grid tree-data="policies"></tree-grid>
但是当我点击删除链接时,我什么也没得到,它没有进入 Controller 作用域函数(
但是为什么呢?我做错了什么?
我可以用脏的方式写这个函数在指令中,但这是一个坏主意((
如何解决?
最佳答案
由于 treeGrid 指令使用隔离范围,因此它无法“查看”deleteContent
,除非您通过模板将其传入。
要修复此问题,您需要在模板中定义指令时传入函数:
<tree-grid tree-data="policies" delete-content="deleteContent(branch)"></tree-grid>
该函数可以采用当前范围内定义的任何值。这里它正在分支。这可以通过在指令模板中执行以下操作从隔离范围传入:
...
<td> <a ng-click=\"deleteContent({branch: row.branch})\" class=\"action\"><i class=\"glyphicon glyphicon-remove-circle\"></i></a> </td>\
...
我传递的是整个分支,而不仅仅是 id。这是在采用 &
隔离范围值并将 branch
参数(在树网格指令定义中使用)绑定(bind)到 row.branch 的指令中使用的特殊语法指令模板。注意:树形网格内的 branch
必须与指令模板内使用的对象的属性名称匹配(例如 {branch: row.branch})。
这是一个fiddle将deleteContent 传递给指令。单击链接时,它会记录到控制台。
如果这只是指令中保持静态的功能,您可以将其放入指令中的链接函数中:
指令内部:
link: function (scope, element, attrs) {
//...
scope.deleteContent = function () {
console.log("Content deleted");
}
//...
}
关于javascript - Angular js : call parent controller method from directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659443/