我的目标是从一段文本中提取所有主题标签并用指令替换它们,这意味着它应该从这里开始:
<p>Hello #stackoverflow this is a #test<p>
进入
<p>Hello <hashtag="stackoverflow"></hashtag> this is a #test<p>
我的想法是使用过滤器用指令 html 替换主题标签,但我不知道如何显示它,因为 ng-bind-html-unsafe 显然没有编译指令。
有什么提示吗?
最佳答案
创建一个新指令,将 HTML 字符串附加到 DOM 后将其编译为模板:
angular.module('myCompile', [], ['$compileProvider', function($compileProvider) {
// Allows an attribute's value to be evaluated and compiled against the scope, resulting
// in an angularized template being injected in its place.
//
// Note: This directive is suffixed with "unsafe" because it does not sanitize the HTML. It is up
// to the developer to ensure that the HTML is safe to insert into the DOM.
//
// Usage:
// HTML: <div my-compile-unsafe="templateHtml"></div>
// JS: $scope.templateHtml = '<a ng-onclick="doSomething()">Click me!</a>';
// Result: DIV will contain an anchor that will call $scope.doSomething() when clicked.
$compileProvider.directive('myCompileUnsafe', ['$compile', function($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.myCompileUnsafe);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM element
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}]);
}]);
关于javascript - Angularjs - 带有 ng-bind-html-unsafe 的内联指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18063280/