angular js - HTML returned from a service function in a ng-repeat renders as text

StackOverflow https://stackoverflow.com/questions/23687902

  •  23-07-2023
  •  | 
  •  

When I call a function, that provides a block of HTML, from within an ng-repeat, it is rendering as text, but I would like this to render the HTML. How should I approach this? :

<tr ng-repeat="person in data.people">
   <td class="text-left">
       {{getInitials(person.Firstname, person.Surname, person.IconColor )}}
   </td>
</tr>

I have a function in a service which returns a block of HTML:

angular.module('myapp.services.global', [])
.factory('helperFunctions', function () {
    return {
        getInitials: function (firstname, lastname, iconColor) {
            return "<div style='background-color:" + iconColor + "' class='userIconMedium'>" + firstname.charAt(0) + " " + lastname.charAt(0) + "</div>";
        }
    }
});
有帮助吗?

解决方案

I mentioned that this is a perfect place for a directive however I realize that directives can be difficult to understand at first glance. Directives are used to link in with the DOM. Rendering HTML within Angular should usually be limited to directives.

You would modify your HTML to have the directive.

<tr ng-repeat="person in data.people">
    <td class="text-left">
       <div myapp-initials="person" ></div>
    </td>
 </tr>

Your angular module would no longer contain a factory definition but a directive definition.

angular.module('myapp.directives', [])
.directive('myappInitials', function () {
  return {
    restrict: 'A',
    template: "<div style='background-color:{{myappInitials.IconColor}}' class='userIconMedium'>{{myappInitials.Firstname.charAt(0) + ' ' + myappInitials.Surname.charAt(0)}}</div>",
    scope: {
      myappInitials: "="
    }
  };
});

I have created a plunker to demonstrate how to use a directive in your situation.

其他提示

Further to this, the above accepted answer is not quite correct. IE (including 11) does not support interpolation in style attributes. You must use ngStyle for that, e.g ng-style="{'background-color': myAppInitials.IconColor}"

https://docs.angularjs.org/guide/ie

This is my working solution based on the directive kindly provided by @Joel above, though I'd prefer to include the ng-style element within the template of the directive but I am not yet sure whether this is possible:

<tr ng-repeat="person in data.people">
    <td class="text-left">
       <div ng-style="{'background-color':person.IconColor}" class="userIconMedium" myapp-initials="person"></div>
    </td>
</tr>

The directive:

angular.module('myapp.directives', [])
    .directive('myappInitials', function () {
       return {
          restrict: 'A',
          template: "{{myappInitials.Firstname.charAt(0) + ' ' + myappInitials.Surname.charAt(0)}}",
          scope: {
             myappInitials: "="
          }
};
 });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top