Compiling dynamic HTML strings from database

前端 未结 5 1302
花落未央
花落未央 2020-11-22 02:14

The Situation

Nested within our Angular app is a directive called Page, backed by a controller, which contains a div with an ng-bind-html-unsafe attribute. This is

5条回答
  •  误落风尘
    2020-11-22 03:00

    In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

    I fixed that by fetching the attribute from the scope property

     scope: { dynamic: '=dynamic'}, 
    

    My example

    angular.module('app')
      .directive('dynamic', function ($compile) {
        return {
          restrict: 'A',
          replace: true,
          scope: { dynamic: '=dynamic'},
          link: function postLink(scope, element, attrs) {
            scope.$watch( 'dynamic' , function(html){
              element.html(html);
              $compile(element.contents())(scope);
            });
          }
        };
      });
    

提交回复
热议问题