如何从 Angular 的指令中引发事件?我正在考虑类似于 ng-click 的东西。
例如,我正在尝试创建将引导菜单包装为上下文菜单指令。我想要一个在单击项目时触发的事件。我通过将控制器中的单击事件设置为指令的范围属性并从指令内部调用它来使其工作。这是“正确”的做法吗?
HTML:
<div ng-app='App'>
<div ng-controller="MyCtrl">
Item Clicked: {{item}}
<ul context-menu class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" context-click="onClick">
<li><a tabindex="-1" href="#" ng-click="contextMenuClick('Action')">Action</a></li>
<li><a tabindex="-1" href="#" ng-click="contextMenuClick('Another action')">Another action</a></li>
<li><a tabindex="-1" href="#" ng-click="contextMenuClick('Something else')">Something else here</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#" ng-click="contextMenuClick('Separated link')">Separated link</a></li>
</ul>
</div>
</div>
var app = angular.module('App',[]);
app.controller('MyCtrl', function ($scope) {
$scope.item = "";
$scope.onClick = function(item) {
$scope.item = item;
};
});
Javascript:
var app = angular.module('App',[]);
app.controller('MyCtrl', function ($scope) {
$scope.item = "";
$scope.onClick = function(item) {
$scope.item = item;
};
});
app.directive("contextMenu", function () {
return {
restrict: 'A',
scope: {
contextClick: '='
},
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, iElement, iAttrs, controller) {
scope.contextMenuClick = function (item) {
scope.contextClick.call(scope.$parent, item);
};
// Show the menu
iElement.css({
display: 'block',
top: '100px'
});
}
};
}
};
});