javascript - 覆盖 Angular 指令链接

标签 javascript angularjs

我对 Angular 的了解有限,所以请耐心等待。我所处的情况是,我只能修改一个 js 文件,该文件包含在所有 Angular 内容之前。有一个指令导致了问题,但我无法直接修改它。因此,我尝试通过在文档就绪 block 中添加下面的代码片段来覆盖它:

app.directive('selectionChange', function($rootScope){
   return {
      priority: 1,
      terminal: true,
      link: function(scope, el, attr) {
         console.log('works');
      };
   };
});

我可以看到该指令添加到了 invokeQueue 的末尾,但它从未被执行。我如何附上这个?谢谢!

更新:

抱歉,让我试着澄清一下。问题是,原始指令继续触发,但新附加的指令却没有(通过使用 console.log 和警报进行测试)。标记是这样的:

<html>
<head>
...
<script src="[the file I can modify].js"></script>
...
</head>
<body>
...
<script src="angular.js"></script>
<script src="directives.js"></script> // here is where the existing selectionChange directive is defined
...
</body>
</html>

最佳答案

这是a plunker

$(function () {
  var app = angular.module('app');

  app.config(function ($provide) {
    $provide.decorator('badDirective', function ($delegate) {
      var badDirective = $delegate[0];

      var link = function (scope, element) {
        element.text('good');
      }

      var originalCompile = badDirective.compile || function () {};
      badDirective.compile = function () {
        originalCompile.apply(badDirective, arguments);

        // compile returns link fn, directive 'link' property will be ignored anyway
        return link;
      }

      return $delegate;
    });    
  });
})

在“就绪”状态(例如 jQuery ready 实现)执行此操作是正确的。这样,代码将在引导过程之前启动(一旦加载 angular.js,它将通过 ng-app 进入“就绪”队列)。

bad 指令只是内部的 badDirective 服务,其中包含一个 DDO 数组(因为可以有多个同名指令)。而且它可以像任何其他服务一样进行装饰。

链接函数可以使用linkcompile(它可以返回链接)DDO属性来定义。第二个会覆盖第一个,因此在装饰指令时始终坚持compile

关于javascript - 覆盖 Angular 指令链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685003/

相关文章:

javascript - 在 onChange/onClick 之后 React 重新渲染部分页面

javascript - 窗口加载后如何分配变量值

javascript - 从第三方库导入 javascript 模块

javascript - 单击图像或 iframe 时交换 div 内容 (Vimeo)

javascript - Angular 单元测试 Controller $scope长度

javascript - Canvas 和 Container SigmaJS 之间的大小不同

javascript - 单击 map 时 agm-snazzy-info-window 将关闭

javascript - 我可以/应该在 cordova 应用程序中下载 html5 代码吗?

javascript - 如何删除值的格式化掩码

javascript - 使用 ng-model-options updateOn :blur with uib-datepicker popup