我有一个 html 片段,它来自 Angular 服务检索的 mongo db。ng-bind-html
然后使用来自 ngSanitize的指令在我的页面上清理这个 html 片段。我想知道如何将 html 片段中的表达式绑定到页面,以便当我绑定 html 时,绑定表达式在片段中执行。例如,这里是我的 div,我的 html 片段将绑定到:
<div ng-bind-html="middle_snippet">
</div>
这是从服务中获取的实际代码片段。
<p>WHY HERRRRO!!! {{myBinding}}</p>
这是我的简单控制器:
var middleMainContent = $Content.content({slug: "home-bottom-middle"
}, function () {
console.log(JSON.stringify(middleMainContent));
$scope.middle_snippet = middleMainContent.response.content.snippet;
$scope.myBinding = 'VERY NICE BINDING';
});
所以我的预期结果真的是html:
为什么是赫罗!!!非常好的装订
但是我得到了带有花括号的原始 html。任何想法都会有所帮助,因为我一直在这里试图让它发挥作用。
更新:所以在阅读了编译服务并将它们与指令一起使用之后,正如 Chandermani 所提到的,我既开明又困惑。AngularJS 团队在使用 $compile 时的“最佳实践”方式是在指令定义对象(DDO)中使用它,如此处所述http://docs.angularjs.org/api/ng/service/$compile。好的,所以我创建了一个 DDO,但是,我对 DDO 的 compile: 方法中的内容感到困惑。这是我到目前为止所拥有的:
var myModule = angular.module('html_compile');
myModule.directive('html_compiler', function factory(injectables) {
var directiveDefinitionObject = {
priority: 0,
template: $scope.snippet,
replace: true,
transclude: false,
restrict: 'E',
scope: false,
compile: function compile(tElement, tAttrs) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
// or
// return function postLink( ... ) { ... }
},
// or
// link: {
// pre: function preLink(scope, iElement, iAttrs, controller) { ... },
// post: function postLink(scope, iElement, iAttrs, controller) { ... }
// }
// or
// link: function postLink( ... ) { ... }
};
return directiveDefinitionObject;
});