Insert HTML into view from AngularJS controller

前端 未结 18 1853
Happy的楠姐
Happy的楠姐 2020-11-21 06:00

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?

This comes from a requirement to turn an

18条回答
  •  梦谈多话
    2020-11-21 06:43

    Another solution, very similar to blrbr's except using a scoped attribute is:

    angular.module('app')
    .directive('renderHtml', ['$compile', function ($compile) {
        return {
          restrict: 'E',
          scope: {
            html: '='
          },
          link: function postLink(scope, element, attrs) {
    
              function appendHtml() {
                  if(scope.html) {
                      var newElement = angular.element(scope.html);
                      $compile(newElement)(scope);
                      element.append(newElement);
                  }
              }
    
              scope.$watch(function() { return scope.html }, appendHtml);
          }
        };
      }]);
    

    And then

    
    

    Note you may replace element.append() with element.replaceWith()

提交回复
热议问题