2015-10-20 30 views
3

我正在编写一个从模板创建文本的指令,但是我无法将我的最终结果呈现为HTML。这是指令:AngularJS:在指令控制器中呈现HTML

.directive('description', function($timeout){ 
    function descriptionCtrl(){ 
    var self = this; 
    self.result = ""; 
    self.init = function(value) { 
     console.log("template in directive",value); 
     self.finalValue = "<div>HI <input type='text' id='hi' /></div>"; 
    }; 
    } 
    return { 
    restrict: 'AE', 
    controller : descriptionCtrl, 
    controllerAs: 'dc', 
    scope: { 
     text: "=" 
    }, 
    replace: true, 
    template: "<div id='template'>{{dc.finalValue}}</div>", 
    link: function(scope, iElement, iAttrs, ctrl) { 
     scope.$watch("text", function(value){ 
     if(value!==undefined){ 
      $timeout(ctrl.init(value),0); 
     } 
     }); 
    } 
    } 
}); 

数据来自控制器,一旦用户选择了一些选项,因此$ watch。

谢谢!

回答

2

您应该使用ng-bind-html绑定HTML到div

template: "<div id='template' ng-bind-html='dc.finalValue'></div>", 
+1

完美,谢谢!我必须在模块中添加'ngSanitize',并在接受输入时添加$ sce.trustAsHtml(value)。 – Ramon

+1

@Ramon这很酷:) –