绑定新的HTML调用trustAsHtml Angularjs后控制器 [英] Bind new html to controller after calling trustAsHtml Angularjs
问题描述
我能够嵌入一旦从服务器接收到的新的HTML,但后来我需要将其绑定到模型。甚至当我编译5秒它插入并显示HTML不绑定到模型后。
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.
让我简要地体现它
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;
});
}
}
让我们假设HTML是
<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>
的HTML是正确嵌入,但我想将它绑定到模型。
The html is embedded correctly but I want to bind it to the model.
推荐答案
看看答案<一个href=\"http://stackoverflow.com/questions/20297638/call-function-inside-sce-trustashtml-string-in-angular-js\">this相关的问题,其中描述了使用指令编译模板:
Take a look at the answer to this related question, which describes using a directive to compile the template:
这是一个有点棘手,因为NG-绑定-HTML将只需插入普通的旧html和不打扰编译它(HTML中,所以任何指令不会被角处理。
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.
下面是一个 演示 ,纳入建议技术与code。
Here's a demo, incorporating the suggested technique with your code.
这篇关于绑定新的HTML调用trustAsHtml Angularjs后控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!