我有一个元素,我想把html绑定到它上。
<div ng-bind-html="details" upper></div>
这是可行的。现在,我还有一个绑定到绑定的html的指令:
$scope.details = 'Success! <a href="#/details/12" upper>details</a>'
但是带有div和锚的指令upper
不求值。我该如何让它工作呢?
发布于 2013-07-02 21:14:02
我也面临着这个问题,在互联网上搜索了几个小时后,我读到了@Chandermani的评论,这被证明是解决方案。您需要使用此模式调用'compile‘指令:
HTML:
<div compile="details"></div>
JS:
.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
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);
}
);
};
}])
您可以看到一个有效的fiddle of it here
发布于 2013-12-07 01:57:18
谢谢你对vkammerer的精彩回答。我建议的一种优化是在编译运行一次后取消监视。监视表达式中的$eval可能会影响性能。
angular.module('vkApp')
.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
var ensureCompileRunsOnce = scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
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);
// Use un-watch feature to ensure compilation happens only once.
ensureCompileRunsOnce();
}
);
};
}]);
发布于 2015-08-07 22:28:43
添加此指令angular-bind-html-compile
.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
// Incase value is a TrustedValueHolderType, sometimes it
// needs to be explicitly called into a string in order to
// get the HTML string.
element.html(value && value.toString());
// If scope is provided use it, otherwise use parent scope
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
像这样使用它:
<div bind-html-compile="data.content"></div>
非常简单:)
https://stackoverflow.com/questions/17417607
复制相似问题