我如何在 angularjs 中创建一个指令,例如采用此元素:
<div>Example text http://example.com</div>
并将其转换为此
<div>Example text <a href="http://example.com">http://example.com</a></div>
我已经编写了自动链接函数中的文本并返回 html 的功能(我们将函数称为“autoLink”),但我还没有达到我的指令要求。
我还想向元素添加一个属性,以将对象传递给指令。例如
<div linkprops="link.props" >Example text http://example.com</div>
其中 link.props 是类似 {a: 'bla bla', b: 'waa waa'} 的对象,它将作为第二个参数传递给 autoLink 函数(第一个参数是文本)。
最佳答案
有两种方法:
指令
app.directive('parseUrl', function () {
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
return {
restrict: 'A',
require: 'ngModel',
replace: true,
scope: {
props: '=parseUrl',
ngModel: '=ngModel'
},
link: function compile(scope, element, attrs, controller) {
scope.$watch('ngModel', function (value) {
var html = value.replace(urlPattern, '<a target="' + scope.props.target + '" href="$&">$&</a>') + " | " + scope.props.otherProp;
element.html(html);
});
}
};
});
HTML:
<p parse-url="props" ng-model="text"></p>
过滤器
app.filter('parseUrlFilter', function () {
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
return function (text, target, otherProp) {
return text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>') + " | " + otherProp;
};
});
HTML:
<p ng-bind-html-unsafe="text | parseUrlFilter:'_blank':'otherProperty'"></p>
注意:'otherProperty'
只是举例,以防您想将更多属性传递到过滤器中。
<强> jsFiddle
更新:改进了替换算法。
关于javascript - Angularjs 指令替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692640/