编辑 2:
有一个没有$watch的解决方案:http://jsfiddle.net/33jQz/18/
指令优先级设置为-1(因为ngBindHtml的优先级为0),并使用$timeout服务在下一个$digest循环中运行逻辑。
编辑 1:
您可以使用指令替换 div 中的子 a 节点。它设置 $watch 检查 div 内新 <a> 元素的长度,然后剪切 href 属性并添加新属性 - ng-click="open()"。它在元素上使用$compile 服务来使ng-click 工作。
angular.module('ui.directives', []).directive('changeUrl', function ($compile) {
return {
restrict: 'A',
scope: true,
link: function (scope, elem, attrs) {
scope.$watch(function () {
return elem.children('a').length;
}, function () {
if (elem.children('a').length > 0) {
replace();
}
});
function replace() {
var href = elem.children('a').attr('href');
elem.children('a').attr('href', null);
elem.children('a').attr('ng-click', 'open(\''+href+'\')');
$compile(elem.contents())(scope);
}
scope.open = function (url) {
alert(url);
}
}
}
});
由于使用了$watch,它应该可以与传递给 ng-bind-html 的外部 html 内容一起使用。
有一个jsfiddle:http://jsfiddle.net/33jQz/13/
旧答案:
您可以创建一个指令,将您的<a href> 替换为一个新指令
angular.module('ui.directives', []).directive('changeUrl', function () {
return {
restrict: 'A',
scope: true,
template: '<span><a ng-click="open()" ng-transclude></a></span>',
replace: true,
transclude: true,
link: function (scope, elem, attrs) {
var href = attrs.href;
scope.open = function(){
alert(href);
}
}
}
});
使用:
<a change-url href="http://www.externalsite.com">Whatever text</a>
JSFiddle:http://jsfiddle.net/33jQz/8/