我想为 html 字符串中的元素设置 ng-show 或 ng-hide 并将其传递给 ng-bind-html 查看,但 ng-show / ng-hide 不起作用,我的元素始终可见。
这是我的控制器代码:
$scope.my = {
messageTrue: true,
messageFalse: false
};
$scope.HtmlContent = "<div ng-show='{{my.messageFalse}}'>This is incorrect (ng-show & my.messageFalse={{my.messageFalse}})</div> ";
$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
这是我的视图代码:
<div ng-show="my.messageTrue">This is correct (ng-show & my.messageTrue={{my.messageTrue}})</div>
<div ng-hide="my.messageFalse">This is correct (ng-hide & my.messageFalse={{my.messageFalse}})</div>
<div ng-bind-html="trustedHtml"></div>
这是一个 Plnkr http://plnkr.co/edit/tbmULwHdAimLoXJGLnEb?p=preview对于我的问题。 (感谢Xaero https://stackoverflow.com/users/3798176/xaero)
对不起,我的英语不好。谢谢
这是因为您注入的 html 尚未通过 Angular 进行编译和链接,因此它只是“按原样”显示。如果您根本不包含 angular.js,那么它的处理方式与您的标记的处理方式相同。
解决方案是创建一个与 ng-bind-html 类似的指令,但还包括编译和链接 html 片段的步骤。
这个链接 http://ngmodules.org/modules/ng-html-compile是此类指令的一个示例。
这是代码:
angular.module('ngHtmlCompile', []).
directive('ngHtmlCompile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.ngHtmlCompile, function(newValue, oldValue) {
element.html(newValue);
$compile(element.contents())(scope);
});
}
}
});
和用法。
<div ng-html-compile="trustedHtml"></div>
这是工作Plunk http://plnkr.co/edit/C0tl3dluTbSyOQudzyOV?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)