简体   繁体   中英

ng-bind-html not working

I'm trying to insert HTML into my div (bottom of code). 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. I have verified that the service is returning the proper HTML code.

The div is unhidden but no html is displayed.

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:

<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
  • You call a function as HTMLAPI() instead of $scope.HTMLAPI()
  • Your $scope.HTMLAPI() function was also being called before it was initialised

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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