Tuesday, September 17, 2013

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>

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

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]

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>');