我的指令有一个模板,其中包含一个名为content
的范围变量:
<div class="directive-view">
<span class="directive-header">My Directive</span>
{{content}}
</div>
我有以下指令:
(function () {
"use strict";
angular
.module('myApp.myDirective', [])
.directive("myDirective", myDirective);
function myDirective($compile) {
return {
restrict: 'E',
scope: {
},
templateUrl:'../partials/directives/my-directive.html',
controller: function($scope) {
$scope.content = "<span>Some HTML — some more HTML</span>";
},
link: function (scope, element, attrs, ctrl) {
var compiledContent = $compile(scope.content)(scope);
scope.content = compiledContent;
}
};
}
})();
我希望代替{{content}}
看到的是:
Some HTML — some more HTML
我在那里看到的是:
{"0":{"ng339":23},"length":1}
如何将范围字符串的值设置为某个初始值,然后在编译指令时从指令链接中更新它(作为编译后的HTML)?
答案 0 :(得分:2)
这是一个有效的plunker.
首先,改变:
.directive('my-directive')
到
.directive('myDirective')
另外,根据我收集的内容,您希望在编译时使用驻留在指令中的作用域变量将html嵌入到指令模板中。你不需要$compile
。
为此,您需要使用ngBindHtml
,如下所示:
HTML:
<div class="directive-view">
<span class="directive-header">My Directive</span>
><div ng-bind-html="trustAsHtml(content)"></div>
</div>
指令:
function myDirective($compile, $sce) {
return {
restrict: 'E',
scope: {
},
template: '../partials/directives/my-directive.html',
controller: function($scope) {
$scope.content = "<span>Some HTML — some more HTML</span>";
},
link: function (scope, element, attrs, ctrl) {
scope.trustAsHtml = function(val) {
return $sce.trustAsHtml(val);
}
}
};
}
答案 1 :(得分:0)
听起来你想要某种占位符text / html代替content
绑定,直到它被解析并应用。在这种情况下,您最好在模板中修复它:
<div class="directive-view">
<span class="directive-header">My Directive</span>
<span ng-bind-html="content">Some HTML — some more HTML</span>
</div>
是的,.directive("my-directive", myDirective);
应该是.directive("myDirective", myDirective);
,但我想这只是错字。