角度指令编译/链接未被调用

angular directive compile/link not getting called

本文关键字:调用 链接 指令 编译      更新时间:2023-09-26

我正在尝试捕获所有锚点点击并使用 href 的。所以我写了下面的指令

app.directive('a', function() {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs) {
                if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
                    elem.on('click', function(e){
                        alert(attrs.href);
                        e.preventDefault();
                    });
                }
            }
        };
    })

我尝试在我的应用程序.js以及 MyCtrl.js 文件中提供这个。我的模块声明在 myCtrl 中是这样的.js:

var AppControllers = angular.module('starter.controllers');
AppControllers

它在另一个离子项目中工作。不知道我哪里出错了。有人可以帮助我吗?

阅读评论后更新了答案

您可以覆盖 a 指令。但是,您必须确保覆盖默认行为,以防止 angularjs 覆盖的锚点选项卡单击处理程序触发。

app.directive('a', function() {
  return {
    restrict: 'E',
    scope: true,
    compile: function(element, attr) {
      element.bind('click', function(event) {
        alert('clicked on link: ' + attr.href)
        event.preventDefault(); // IMPORTANT
      });
    }
  }
});

此外,在尝试绑定到 html 时,您可能希望确保编译它以确保锚标记指令启动。有一个指令可以为您完成:

app.directive('bindHtmlCompile', ['$compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      scope.$watch(function() {
        return scope.$eval(attrs.bindHtmlCompile);
      }, function(value) {
        element.html(value);
        $compile(element.contents())(scope);
      });
    }
  };
}]);

来源: https://stackoverflow.com/a/29994559/841804

因此,您可以像这样使用bind-html-compile而不是ng-bind-html

<span bind-html-compile="getHtml()"></span>

最后,这里有一个 plunker 可以做到这一点:http://plnkr.co/edit/efJw8f40gYIaXo5Bdv44?p=preview