用于替换文本的 Angularjs 指令 [英] Angularjs directive to replace text
问题描述
我将如何在 angularjs 中创建一个指令,例如采用此元素:
How would I create a directive in angularjs that for example takes this element:
<div>Example text http://example.com</div>
然后把它转换成这个
<div>Example text <a href="http://example.com">http://example.com</a></div>
我已经编写了自动链接函数中的文本并返回 html 的功能(让我们将函数称为 "autoLink" ),但我对我的指令不满意.
I already have the functionality written to auto link the text in a function and return the html (let's call the function "autoLink" ) but i'm not up to scratch on my directives.
我还想向元素添加一个属性以将对象传递给指令.例如
I would also like to add a attribute to the element to pass a object in to the directive. e.g.
<div linkprops="link.props" >Example text http://example.com</div>
其中 link.props 是像 {a: 'bla bla', b: 'waa waa'} 这样的对象,它将作为第二个参数(第一个是文本)传递给 autoLink 函数.
Where link.props is object like {a: 'bla bla', b: 'waa waa'} which is to be passed to the autoLink function as a second param (the first been the text).
推荐答案
两种方法:
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'
只是举例,以防您想将更多属性传递到过滤器中.
Note: The 'otherProperty'
is just for example, in case you want to pass more properties into the filter.
更新:改进了替换算法.
这篇关于用于替换文本的 Angularjs 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!