AngularJS - 如何覆盖指令 ngClick [英] AngularJS - how to override directive ngClick
问题描述
我想覆盖指令 ng-click: 在每次执行 ng-click 之前进行一些 $rootscope 更改.怎么做?
I want to override directive ng-click: to some make some $rootscope changes before each execution of ng-click. How to do it?
推荐答案
您不能覆盖 AngularJS 内置指令.但是,您可以定义多个具有相同名称的指令,并针对同一个元素执行它们.通过为指令分配适当的 priority
,您可以控制指令是在内置指令之前还是之后运行.
You can't override AngularJS built-in directives. However, you can define multiple directives with the same name and have them executed against the same element. By assigning appropriate priority
to your directive, you can then control whether your directive runs before or after a built-in directive.
这个 plunker 展示了如何构建一个在之前执行的 ng-click
指令内置的 ng-click
可以.代码也如下所示.单击链接时,自定义 ng-click
将首先运行,然后内置 ng-click
运行.
This plunker shows how to build an ng-click
directive that executes before the built-in ng-click
does. The code is also shown below. When clicking the link, the custom ng-click
will run first, then the built-in ng-click
does.
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="jquery@1.9.0" data-semver="1.9.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
<script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MyCtrl">
<a ng-click="alert()">Click me</a>
</body>
</html>
script.js
angular.module('app', [])
.directive('ngClick', function($rootScope) {
return {
restrict: 'A',
priority: 100, // give it higher priority than built-in ng-click
link: function(scope, element, attr) {
element.bind('click', function() {
// do something with $rootScope here, as your question asks for that
alert('overridden');
})
}
}
})
.controller('MyCtrl', function($scope) {
$scope.alert = function() {
alert('built-in!')
}
})
这篇关于AngularJS - 如何覆盖指令 ngClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!