调用 trustAsHtml Angularjs 后将新的 html 绑定到控制器 [英] Bind new html to controller after calling trustAsHtml Angularjs
问题描述
一旦从服务器收到新的 html,我就可以嵌入,但稍后我需要将它绑定到模型.即使我在插入并显示 5 秒后编译它,html 也不会绑定到模型.
让我简单地举例说明
function coolController($scope, $http, $log, $sce, $compile, $timeout){$scope.message = {错误:'内核恐慌!:)',其他信息:''}$scope.form = $sce.trustAsHtml('<div></div>');$scope.Init = function(){$http({方法:'获取',url: helper.url('/form')}).成功(功能(数据,状态,标题,配置){$scope.form = $sce.trustAsHtml(data);$超时(功能(){$compile(angular.element('#elemThatContainsTheNewHTML'))($scope);}, 2500);}).错误(功能(数据,状态,标题,配置){$scope.message.error = 数据;});}}
假设 html 是
我很酷的错误:{{ message.error }}
它嵌入的地方应该是这样的:
<h4>你好???</h4><div ng-init="Init()"><span class="alert-error" ng-if="errorMessage.length > 0">{{errorMessage}}</span><div id="elemThatContainsTheNewHTML" class="viewContent" ng-bind-html="form">
html 已正确嵌入,但我想将其绑定到模型.
看一下 这个相关问题,它描述了使用指令来编译模板:
<块引用>这有点棘手,因为 ng-bind-html 只会插入普通的旧 html 而不会费心编译它(因此 html 中的任何指令都不会被 angular 处理.
这是一个演示,其中包含了建议的技术使用您的代码.
I'm able to embed the new html once received from the server but later I need to bind it to the model. Even when I compile it 5 seconds after it's inserted and displayed the html does not bind to the model.
Let me exemplify it briefly
function coolController($scope, $http, $log, $sce, $compile, $timeout){
$scope.message = {
error: 'Kernel panic! :)',
otherInfo: ''
}
$scope.form = $sce.trustAsHtml('<div></div>');
$scope.Init = function(){
$http({
method: 'GET',
url: helper.url('/form')
}).
success(function(data, status, headers, config) {
$scope.form = $sce.trustAsHtml(data);
$timeout(function(){
$compile(angular.element('#elemThatContainsTheNewHTML'))($scope);
}, 2500);
}).
error(function(data, status, headers, config) {
$scope.message.error = data;
});
}
}
Let's assume the html is
<div>
My cool error: {{ message.error }}
</div>
and the place where it's embedded should seem like:
<div ng-controller="coolController">
<h4>Hello???</h4>
<div ng-init="Init()">
<span class="alert-error" ng-if="errorMessage.length > 0">{{errorMessage}}</span>
</div>
<div id="elemThatContainsTheNewHTML" class="viewContent" ng-bind-html="form">
</div>
</div>
The html is embedded correctly but I want to bind it to the model.
Take a look at the answer to this related question, which describes using a directive to compile the template:
It's a bit tricky because ng-bind-html will simply insert plain old html and not bother compiling it (so any directives in the html will not be processed by angular.
Here's a demo, incorporating the suggested technique with your code.
这篇关于调用 trustAsHtml Angularjs 后将新的 html 绑定到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!