如何在 AngularJS 中动态生成的 HTML 中用 ngClicks 替换 link hrefs?

How can I replace link hrefs with ngClicks in dynamically generated HTML within AngularJS?

我正在使用从可能包含超链接的 API 动态生成的 HTML,我想用 ngClicks 替换其中的 href。当我在 DOM 检查器中检查它时,以下指令似乎按预期修改了 HTML,但单击它没有任何反应。我做错了什么?

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

                element.html(value);

                angular.forEach(element.contents().find("a"), function(link) {
                    link.removeAttribute("href");
                    link.removeAttribute("target");
                    link.setAttribute("ng-click", "alert('test')");
                });

                $compile(element.contents())(scope);
            });
        }
    };
}]);

不要删除 href,请将其设置为 blank(这将保留 link css),同时 ng-click 调用警报可以通过在范围方法中调用 alert('test') 来完成,为什么警报没有触发,在这个 中有解释,请参考下面的示例代码!

// <body ng-app='myApp' binds to the app being created below.
var app = angular.module('myApp', []);
app.directive('replaceLinks', ['$compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      angular.forEach(element.find("a"), function(link) {
        link.setAttribute("href", "");
        link.removeAttribute("target");
        link.setAttribute("ng-click", "scopeAlert('test')");
      });
      $compile(element.contents())(scope);


    }
  };
}]);
// Register MyController object to this app
app.controller('MyController', ['$scope', MyController]);

// We define a simple controller constructor.
function MyController($scope) {
  // On controller load, assign 'World' to the "name" model
  // in <input type="text" ng-model="name"></input>
  $scope.name = 'World';
  $scope.scopeAlert = function(name) {
    window.alert(name);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <div replace-links>
    <a href="#">test 1</a>
    <a href="#">test 2</a>
    <a href="#">test 3</a>
  </div>
</div>