当我单击表格单元格时,我需要实现上下文菜单。
我尝试过这个看起来不错的模块:https://github.com/ds82/angular-contextmenu
但是当我尝试使用它时:
<table class="table table-bordered" contextmenu-container="main.contextmenu">
<tbody>
<tr ng-repeat="facture in factures" contextmenu-item="facture">
...
我在右键单击事件时收到此错误:
TypeError: undefined is not a function at http://localhost:8080/assets/js/directives/contextmenu.js:74:27
错误的指令是:
app.directive('contextmenuItem', [function() {
return {
restrict: 'A',
require: '^contextmenuContainer',
scope: false,
link: function( $scope, $element, $attrs, contextMenuCtrl ) {
var iam = $scope[( $attrs.contextmenuItem )];
$element.on( pointerEvents, function( event ) {
$scope.$apply(function() {
contextMenuCtrl.open( iam, event );
});
event.stopPropagation();
return false;
});
}
}
}]);
它在这一行崩溃:
contextMenuCtrl.open( iam, event );
有人使用这个模块吗?这是一个已知问题吗?
最佳答案
当前您的问题是您在属性内传递 facture
对象,该属性是元素之一,您永远不会在作用域内使用 facture
变量,因为它是一个事实
的一部分。这就是为什么当您执行 var iam = $scope[( $attrs.contextmenuItem )];
时,iam
的值未定义。
The reason behind it crashes at line
contextMenuCtrl.open( iam, event );
because yourcontextMenuCtrl
doesn't have methodopen
in that directive controller
我建议您传递使用隔离范围,因为您想跟踪使用ng-repeat
呈现的facture
,然后您的隔离范围将有 facture : '='
会将 facture
对象传递给指令
指令
app.directive('contextmenuItem', [function() {
return {
restrict: 'A',
require: '^contextmenuContainer',
scope: {
facture: '='
},
link: function( $scope, $element, $attrs, contextMenuCtrl ) {
//var iam = $scope[( $attrs.contextmenuItem )];
$element.on( pointerEvents, function( event ) {
$scope.$apply(function() {
//`contextMenuCtrl` should have method open in its controller
contextMenuCtrl.open( $scope.facture, event );
});
event.stopPropagation();
return false;
});
}
}
}]);
您的 contextmenuContainer
指令代码应如下所示。必须具有与该指令关联的 Controller ,并且必须包含范围内定义的 open 方法。
contextmenuContainer指令
app.directive('contextmenuContainer', [function() {
return {
restrict: 'A',
scope: {},
link: function($scope, $element, $attrs, contextMenuCtrl) {
//if its there you can have code here
},
controller: function($scope) { //this must be here-
//the methods defined here will be exposed to the directive
//which inherits it using require.
$scope.open = function() {
//code here
};
//you could have other methods to.
}
}
}]);
关于javascript - Angularjs - 表格单元格上的上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751599/