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/], I recognize that doing an element.html(databaseString) will render correctly in the browser, but I needed to use $compile to get the string to be fully "jammed" into the DOM. Once I added the $compile, like Tim Sommer suggested!, the .directive('rel'...) is now firing! But, when the .directive gets the compiled the element value is now "empty", e.g.:
<span rel="webResource" resource="http://www.stackflow.com">Stack Flows Home</span>
is now <span rel="webResource" resource="http://www.stackflow.com"></span>
Interestingly, the $compile actually triggers the 'rel' directive immediately and it runs before the next statement in the 'displayString' executes.
Any idea why the value/text of the has gone missing? So, progress, but still stuck!