问题描述
我想在 html 字符串中为我的元素设置 ng-show 或 ng-hide 并将其传递给使用 ng-bind-html 查看但 ng-show/ng-hide 不起作用并且我的元素始终可见.
这是我的控制器代码:
$scope.my = {消息真:真,消息错误:错误};$scope.HtmlContent = "<div ng-show='{{my.messageFalse}}'>这是不正确的 (ng-show & my.messageFalse={{my.messageFalse}})</div>";$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
这是我的视图代码:
<div ng-show="my.messageTrue">这是正确的 (ng-show & my.messageTrue={{my.messageTrue}})</div><div ng-hide="my.messageFalse">这是正确的 (ng-hide & my.messageFalse={{my.messageFalse}})</div><div ng-bind-html="trustedHtml"></div>
这是我的问题的 Plnkr.(感谢 Xaero)
抱歉我的英语不好.谢谢
这是因为您正在注入的 html 尚未通过 angular 编译和链接,因此它只是按原样"显示.如果您根本不包含 angular.js,则它的处理方式与您的标记的处理方式相同.
解决方案是创建一个类似于 ng-bind-html 的指令,但还包括编译和链接 html 片段的步骤.
此链接 是此类指令的一个示例.
代码如下:
angular.module('ngHtmlCompile', []).指令('ngHtmlCompile',函数($compile){返回 {限制:'A',链接:函数(范围,元素,属性){scope.$watch(attrs.ngHtmlCompile, function(newValue, oldValue) {element.html(newValue);$compile(element.contents())(scope);});}}});
和用法.
这是有效的 Plunk
I want to set ng-show or ng-hide for my elements in html string and pass it to view with ng-bind-html but ng-show / ng-hide not working and my element always visible.
This is my controller code:
$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);
And this is my view code:
<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>
This is a Plnkr for my question. (Thanks for Xaero)
Sorry for my bad English. Thanks
This is because the html you are injecting has not yet been compiled and linked by angular, so it is just being displayed "as is". It's being treated the same way your markup would be treated if you didn't include angular.js at all.
The solution is to create a directive that works similar to ng-bind-html, but that also includes a step for compiling and linking the html fragment.
This link is an example of such a directive.
Here is the code:
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);
});
}
}
});
and the usage.
<div ng-html-compile="trustedHtml"></div>
And here is the working Plunk
这篇关于angular ng-show/ng-hide 无法与 ng-bind-html 一起正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!