gpt4 book ai didi

javascript - ng-bind-html 和 ng-controller

转载 作者:搜寻专家 更新时间:2023-10-31 23:24:56 24 4
gpt4 key购买 nike

我正在向某些 <div> 中注入(inject)不安全的 html ,像这样:

<div class="category-wrapper" ng-bind-html="content"></div>

这个 html 有 angularjs“代码”($scope.content 加载了类似这样的东西):

<script type='text/javascript' src='giveus.js'></script>
<div class="giveus-wrapper" ng-controller="GiveUsController">{{variable1}}</div>

请注意,此代码段有 ng-controller . GiveUsController 在嵌入 html(不在头部)的同时延迟加载。声明此 Controller 没有错误,因为它已经过测试。

我的 Controller 很简单:

angular.module("tf").controller('GiveUsController', function ($scope, $http)    
{
console.debug("GiveUsController loaded");
$scope.variable1 = "hi!";
}

没有控制台调试,也没有 variable1作业

看起来没有 Controller 绑定(bind)到 <div> .

我不知道如何用 Angular Controller 注入(inject) html 并使其工作...

有什么想法吗?

最佳答案

您可以通过一些手动 html 编译来做您想做的事。这是一种本质上是 $compile service 的指令包装器的方法。 .观察以下示例和用法...

 <div class="category-wrapper" ng-html="content"></div>

.controller('ctrl', function($scope) {
$scope.content = '<div class="giveus-wrapper" ng-controller="GiveUsController">{{variable1}}</div>'
})
.controller('GiveUsController', function($scope) {

console.log('hello from GiveUsController')
$scope.variable1 = 'I am variable 1'
})
.directive('ngHtml', ['$compile', function ($compile) {
return function (scope, elem, attrs) {
if (attrs.ngHtml) {
elem.html(scope.$eval(attrs.ngHtml));
$compile(elem.contents())(scope);
}
scope.$watch(attrs.ngHtml, function (newValue, oldValue) {
if (newValue && newValue !== oldValue) {
elem.html(newValue);
$compile(elem.contents())(scope);
}
});
};
}]);

JSFiddle Link - 演示

关于javascript - ng-bind-html 和 ng-controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32849029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com