I have a problem where I retrieve a string with elements in them, I need to rewrite them a elements. The values I need are in attributes of the element. e.g.
<div>The way to find your answer is to go to <span rel="webResource" resource="http://www.stackflow.com">Stack Flows Home</span> webpage.</div>
I had done it in JQuery with a technique like:
jQuery.fn.makeA = function() {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.value;
}
this.replaceWith(function() {
var jqThis = $(this);
return $(document.createElement("a"))
.attr("href", encodeURI(jqThis.attr("resource")))
.attr(attrs)
.append(jqThis.contents());
});
}
and then doing this to the string:
var element = $(spanText);
$("span[rel='webResource']",element).makeA();
return (element[0].outerHTML);
Since I have had to create a Custom Directive in AngularJS for this, is there a good way while in the directive code to implement the same technique without JQuery?
Well, some progress..
I created a customer directive for handling the insertion of the original string:
.directive('displayString'...)
and then after reading this: [ http://blog.timsommer.be/using-compile-to-compile-html-strings-in-angular/]的最佳方法是什么,我认识到执行element.html(databaseString)会在浏览器中正确呈现,但我需要使用$ compile来使字符串完全&#34;卡住&#34;进入DOM。一旦我添加了$ compile,就像Tim Sommer建议的那样!.directive(&#39; rel&#39; ...)现在正在解雇!但是,当.directive得到编译时,元素值现在是&#34;空&#34;,例如:
<span rel="webResource" resource="http://www.stackflow.com">Stack Flows Home</span>
现在是<span rel="webResource" resource="http://www.stackflow.com"></span>
有趣的是,$ compile实际上触发了&#39; rel&#39;立即指令,它在&#39; displayString&#39;中的下一个语句之前运行。执行。
知道为什么价值/文字丢失了吗? 所以,进步,但仍然卡住了!
答案 0 :(得分:0)
需要两个指令。
transclude:yes
并且template
使用ng-transclude
指令并在范围变量中使用{&amp;},因此Angular知道要保留事实字符串嵌入的内容s(和Angular不喜欢传递给$ compile的字符串中的ng-transclude指令!)并从特定的上下文中替换href的值。在@rel
上添加指令非常危险,因为它是标准的RDFa属性,并与HTML指令一起使用。但是,有了守卫条件,没关系。
app.$module.directive('displayFact', ['$compile', function($compile){
return {
restrict: 'E',
scope: { fact : '@'},
link: function (scope, element, attrs) {
var templateInASense = $compile('<span>' + scope.fact + '</span>')(scope); // this triggers the 'rel' directive below, <span> is required to allow $compile to deal with it..
element.replaceWith(templateInASense);
}
}}]);
和指令2:
app.common.$module.directive('rel', [function(){
return {
restrict: 'A',
scope : { reference : '&'},
transclude: true,
template: '<span><a href="{{reference}}" target="_blank"><span ng-transclude /></a></span>',
link: function (scope, element, attrs) {
if (typeof attrs.resource !== "undefined") {
scope.reference= attrs.resource;
}
}
}}]);
模板HTML的片段如下所示:
<td ng-repeat="fact in list"><display-fact fact={{fact.label}}></display-fact></td>
这看起来效果很好。它在单个字符串中处理多个s。它看起来很快。