angular ng-show / ng-hide 无法与 ng-bind-html 一起正常工作

angular ng-show / ng-hide not working correctly with ng-bind-html

我想为 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>

This is a Plnkr for my question. (Thanks for Xaero)

抱歉我的英语不好。谢谢

你有没有在controller中注入$interpolate,并且在module中也加入了ngSanitize?

这是一个有效的 plnkr:http://plnkr.co/edit/qTsUzi04tCNdK5BAZvDa?p=preview

// controller.js
var app = angular.module('app');

app.controller('indexController', indexController);

function indexController($scope, $interpolate) {
  $scope.my = {
    messageTrue: true,
    messageFalse: false
  };

  $scope.HtmlContent = "<div ng-show='{{my.messageTrue}}'>{{my.messageTrue}}</div> ";
  $scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
}

// app.js
angular.module('app', ['ngSanitize']);

// index.html
<!DOCTYPE html>
<html>
<head></head>

<body ng-app="app" ng-controller="indexController">
<div ng-show="my.messageTrue">{{my.messageTrue}}</div>
<div ng-show="my.messageFalse">{{1 + 1}}</div>

<div ng-bind-html="trustedHtml"></div>

<script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-sanitize.js"></script>
<script src="app.js"></script>
<script src="controller.js"></script>
</body>
</html>

和关于使用 ng-bind-html 的 link:How to output html through AngularJS template?

$scope.my = { message: false };
$scope.HtmlContent = "<div ng-show='{{my.message}}'>{{my.message}}</div> ";
$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);

你应该试试这个:

<div ng-show="my.message == false">{{my.message}}</div> 
<div ng-bind-html="trustedHtml"></div> 

这是因为你注入的html还没有被angular编译链接,所以才显示出来"as is"。如果您根本不包含 angular.js,它的处理方式与您的标记的处理方式相同。

解决方案是创建一个类似于 ng-bind-html 的指令,但它还包括编译和链接 html 片段的步骤。

This link 是此类指令的一个示例。

代码如下:

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