简体   繁体   English

ng-bind-html无法正常工作

[英]ng-bind-html not working

I'm trying to insert HTML into my div (bottom of code). 我正在尝试将HTML插入我的div(代码底部)。 I've dealt with an issue like this before so I added a filter. 我之前已经处理过这样的问题,所以我添加了一个过滤器。 However, when the div is made visible through a toggle function the HTML doesn't display from the service. 但是,当通过切换功能使div可见时,HTML不会从服务中显示。 I have verified that the service is returning the proper HTML code. 我已验证该服务正在返回正确的HTML代码。

The div is unhidden but no html is displayed. div未隐藏,但未显示html。

Angular Code: 角度代码:

var myApp = angular.module('myApp', []);
angular.module('myApp').filter('unsafe', function ($sce) {
    return function (val) {
        if ((typeof val == 'string' || val instanceof String)) {
            return $sce.trustAsHtml(val);
        }
    };
});




myApp.controller('myAppController', function ($scope, $http) {
... 
SERVICE CODE 
...

$scope.toggleHTMLResults();
$scope.HTMLjson = obj[0].HTML;    

HTML Code: HTML代码:

<div id="returnedHTML" ng-bind-html="HTMLjson | unsafe " ng-hide="HTMLResults">NOT HIDDEN</div>

I'm not sure why this isn't working. 我不确定为什么这行不通。

Here is my Plunker 这是我的笨蛋

There were multiple things wrong with your example. 您的示例有很多错误。

  • Main Javascript file declared twice, first in header and second before close on body tag 主Javascript文件声明了两次,第一次在标头中,第二次在body标签上关闭之前
  • You call a function as HTMLAPI() instead of $scope.HTMLAPI() 您将函数称为HTMLAPI()而不是$scope.HTMLAPI()
  • Your $scope.HTMLAPI() function was also being called before it was initialised 您的$scope.HTMLAPI()函数也在初始化之前被调用

Fixed controller code: 固定控制器代码:

app.controller('myAppCTRL', ['$scope', '$http', function ($scope, $http) {

    var API = this;
    $scope.HTMLInput = true;
    $scope.HTMLResults = true;

    $scope.toggleHTMLInput = function () {
        $scope.HTMLInput = $scope.HTMLInput === false ? true : false;
    }

    $scope.toggleHTMLResults = function () {
        $scope.HTMLResults = $scope.HTMLResults === false ? true : false;
    }

    $scope.HTMLAPI = function (HTML) {
          var newJSON = ["[{\"ConditionId\":1111,\"ConditionDescription\":\"<i>DATA GOES HERE</i>\",\"ErrorId\":0,\"DisplayId\":0,\"DisplayName\":\"\",\"ErrorValue\":\"\"}]"];
          var obj = JSON.parse(newJSON);
          $scope.HTMLjson = obj[0].ConditionDescription;
          $scope.toggleHTMLResults();

          console.log($scope.HTMLjson);
    }

    $scope.HTMLAPI();
}]);

Working Example 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM