Angularjs 在$sce.trustAsHtml内呈现指令
我在这里包括了一个Plunker: 我正在尝试向DOM中添加一个按钮,单击该按钮时应该执行绑定到它的函数。在这种情况下,它应该提醒测试。这是代码 控制器Angularjs 在$sce.trustAsHtml内呈现指令,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我在这里包括了一个Plunker: 我正在尝试向DOM中添加一个按钮,单击该按钮时应该执行绑定到它的函数。在这种情况下,它应该提醒测试。这是代码 控制器 app.controller('MainCtrl', function($scope, $sce) { $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>'); $
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');
$scope.testAlert = function () {
alert('testing')
};
});
HTML
$sce.trustAsHtml和ng bind html并不意味着使用指令构建html。这种方法行不通
这是因为angular的工作方式是先编译,然后链接。有关详细说明,请参阅
简言之,当您链接trustAsHtml中定义的HTML时,angular编译并理解ng click指令为时已晚
为了动态添加HTML,您应该查看$compile服务和/或指令 对于Angular 1.6.1,我找到了一个适合我的解决方案 模板:
<div ng-bind-html="trustAsHtml(content);" init-bind> </div>
指令:
.directive('initBind', function($compile) {
return {
restrict: 'A',
link : function (scope, element, attr) {
attr.$observe('ngBindHtml',function(){
if(attr.ngBindHtml){
$compile(element[0].children)(scope);
}
})
}
};
})
检查:好的,这里有一个新的plunker,展示了如何使用$compile实现这一点。下面是一些帮助我解决这个问题的其他资源:在表中构建一行并注入包含关键字dynamic指令的html时,这可能吗?我希望您能具体演示如何解决这个问题。如果有人愿意尝试,这也是一个解决方案。太棒了!大量使用指令和$compile。非常感谢。
$scope.trustAsHtml = function(string) {
return $sce.trustAsHtml(string);
};
.directive('initBind', function($compile) {
return {
restrict: 'A',
link : function (scope, element, attr) {
attr.$observe('ngBindHtml',function(){
if(attr.ngBindHtml){
$compile(element[0].children)(scope);
}
})
}
};
})