/* 調用: 在要右鍵點擊的元素上 添加contextMenu屬性便可 */ var app = angular.module('app', []) app.directive('contextMenu', ['$window', function($window) { return { restrict: 'A', //require:'^?ngModel', link: function($scope, element, attrs) { var opened = false; var menuElement = angular.element(document.getElementById(attrs.target)); function open(event, element) { $scope.opened = true; menuElement.css('top', event.clientY + 'px'); menuElement.css('left', event.clientX + 'px'); }; function close(element) { $scope.opened = false; }; $scope.opened = false; //每一個項點擊的事件 $scope.fns = { "查看":function($event){ alert('LOOK'); }, "刷新":function($event){ alert('刷新') } , "點擊":function($event){ alert('點擊') } } //模擬數據填充菜單 數據可通以點擊元素過屬性傳遞過來 //菜單的html 結構 //<ul id='a'><li ng-repeat='m in ms'>{{m.name}}</li></ul> $scope.ms = $scope.model; $scope.fn = function($event,sName){ /* * 根據sName 來判斷使用什麼函數 */ $scope.fns[sName]($event); } //顯示右鍵菜單 element.bind('contextmenu', function(event) { $scope.$apply(function() { event.preventDefault(); open(event, menuElement); }); }); //窗口綁定點擊事件 隱藏右鍵菜單 angular.element($window).bind('click', function(event) { if (opened) { $scope.$apply(function() { event.preventDefault(); close(menuElement); }); } }); } }; }]); //html <body ng-app='app'> <div context-menu target='a' ng-init='model=[{name:"查看"},{name:"刷新"},{name:"點擊"}]'>hello</div> <ul id='a' ng-show='opened'> <li ng-repeat='m in ms' ng-click='fn($event,m.name)'>{{m.name}}</li> </ul> <script src="/javascripts/angular.js"></script> <script src="/javascripts/app.js"></script> </body>