AngularJS how to cast html element

this will usually be used by SharePoint Developers since in angular u have the ngBindHtml.

but in SP u usually get a fields as a complete html like LinkFields or ImageFields and u don't want to put then under a container, like the bindHtml force u, but to put it strait in a template.

so I did this:
<li ng-repeat="item in service.data">
<img cast-me="Image" src="../img/PrePic.JPG"/>
<a href="#" class="linkArrow" cast-me="Link2"></a>
</li>

and my castMe directive:
Module.directive("castMe", function ($compile, $timeout) {
   return {
     link: function (scope, element, attrs) {
       var newElem = angular.element(scope.item[attrs.castMe]);
       $compile(newElem)(scope);
      
if (element.attr('class') !== '')
         newElem.attr('class', element.attr('class'));
       element.replaceWith(newElem);
     }
  };
});


the point is that i am iterating with the ng-repeat, so in my scope i have the item which is the ng-repeat item, and each item contains a property-field with the html, and in cast-me attr i need to put the prop-field name.
remember that you also need to change the name of the item to whatever you are using in the ng-repeat, like if you do ng-repeat="cow in service.herd" so its scope.cow[attrs.castMe]

edit:
i had a case where the html wasn't wrapped with an html tag so i had to do this:
var newElemHtml = scope.item[attrs.castMe]; 
var newElem = angular.element('<div style="display:inline-block"></div>'); 
newElem.html(newElemHtml);
$compile(newElem)(scope);

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

Asp.Net Ending Response options, Response.End() vs CompleteRequest()

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem