AngularJS - 如何覆盖指令ngClick [英] AngularJS - how to override directive ngClick

查看:544
本文介绍了AngularJS - 如何覆盖指令ngClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要重写指令NG-点击:一些使得每次执行前一段$ rootscope变化NG-点击。怎么办呢?

I want to override directive ng-click: to some make some $rootscope changes before each execution of ng-click. How to do it?

推荐答案

您不能覆盖​​AngularJS内置指令。但是,您可以定义多个指令具有相同的名称,并让他们对同一元素执行。通过分配适当的优先级来的指令,就可以控制你的指令是否之前或之后内置指令运行。

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-点击指令之前执行内置 NG-点击一样。在code也是如下图所示。当点击该链接,自定义 NG-点击将先运行,那么内置的 NG-点击一样。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆