一尘不染

AngularJS-如何覆盖指令ngClick

angularjs

我想覆盖指令ng-click:在每次执行ng-click之前进行一些$ rootscope更改。怎么做?


阅读 273

收藏
2020-07-04

共1个答案

一尘不染

您不能覆盖AngularJS内置指令。但是,您可以定义多个具有相同名称的指令,并使它们针对同一元素执行。通过priority为指令分配适当的值,您可以控制指令在内置指令之前还是之后运行。

插件显示了如何构建ng- click在内置指令执行之前执行的指令ng-click。该代码也显示在下面。单击链接时,自定义ng-click将首先运行,然后内置将运行ng- click

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!')
    }
  })
2020-07-04