HTML:
<div ng-app="app">
<test-d class="my-class">this should be replaced</test-d>
</div>
JS:
angular.module('app', []).directive('testD', ['$compile','$sce', function($compile, $sce) {
return {
restrict: 'E',
link: function(scope, element, attrs, controller) {
//"case 1"
//var testElement = angular.element('<div class="{{testClass}}"><div ng-repeat="item in items">{{item.n}}.{{item.label}}</div></div>');
//"case 2"
var testElement = angular.element('<div class="{{testClass}}"><div ng-repeat="item in items">{{item.n}}<div class="how-to-remove-this-div" ng-bind-html="item.label|htmlize"></div></div></div>');
scope.testClass = attrs.class;
scope.items = [
//{n:10,label:$sce.trustAsHtml('<span class="with-icon">label 11</span>')},
// "case 1" of "testElement": no any effects (with "case 1" that would be preferred)
// "case 2" of "testElement": Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html
{n:20,label:'<span class="with-icon">label 22</span>'},
{n:30,label:'<span class="with-icon">label 33</span>'}
];
var testElementCompiled = $compile(testElement)(scope);
//"case 3"
element.replaceWith(testElementCompiled);
//"case 4"
//element.replaceWith($sce.trustAsHtml(testElementCompiled));
}
}
}]).filter('htmlize', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
的jsfiddle: http://jsfiddle.net/isnigirev/c2wRq/
問題: 1)是有可能使用trustAsHtml了過濾器上下文? 2)如果不使用「ng-bind-html」指令的話,如何擺脫「how-to-remove-this-div」類的div?
該文檔(這裏)(http://docs.angularjs.org/api/ng.$sce)給出一個在指令中使用'$ sce'的例子,所以它必須可以在過濾器外使用 – tennisgent
在指令(http://jsfiddle.net/isnigirev/c2wRq/5/)中得到它(trustAsHtml) 。 「錯誤:[$ sce:itype]試圖在需要字符串的內容中信任非字符串值:上下文:html」錯誤發生在我錯誤地嘗試在同一個「標籤」上調用trustAsHtml兩次。 – ivsn
問題的第二部分仍然存在,但我會用一些解決方法解決它。無論如何,解決它也很有趣。 – ivsn