[英]Angular directive to replace external links
如何創建自定義過濾器來替換:
<a href="http://www.externalsite.com">Whatever text</a>
到這個:
<a href="#" ng-click="openExternal('http://www.externalsite.com')">Whatever text</a>
這應該很容易,但是我做不到……我有這個:
<div ng-bind-html="item.htmltext | myFilter"></div>
和item.htmltext包含一些我想以這種方式替換的標記…我應如何創建myFilter來替換鏈接?
編輯2:
有沒有$watch
的解決方案: http : //jsfiddle.net/33jQz/18/
指令優先級設置為-1(因為ngBindHtml的優先級為0),並且通過$timeout
服務在下一個$digest
循環中運行邏輯。
編輯1:
您可以使用指令,它代替孩子a
節點在你的DIV。 它設置$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/
我發現了另一個使用lodash替換所有標簽元素的解決方案:
angular.module('module').directive('changeUrl', function ($compile, $timeout) {
return {
priority: -1,
restrict: 'A',
scope: true,
link: function (scope, elem, attrs) {
$timeout(function() {
var links = elem.find('a');
_.map(links, function (a) {
var href = a.href;
a.setAttribute('ng-click', 'openUrl(\'' + href + '\')');
a.removeAttribute('href');
});
$compile(elem.contents())(scope);
});
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.