【问题标题】:ngBindHtml not Rendering Sanitized HTMLngBindHtml 未呈现经过处理的 HTML
【发布时间】:2015-07-23 15:24:35
【问题描述】:

我有一个简单的 Angular 应用程序,我正在尝试使用 ngBindHtml 将一些 html 注入到页面中。但是,它没有被注入。这是我的 HTML:

<main id="main" ng-bind-html="oreGen | trust"></main>

这是我的 Angular 应用程序:

angular.module('programApp', ['programApp.controllers','programApp.filters','ngSanitize']);

angular.module('programApp.controllers', [])
  .controller('programController', ['$scope', '$filter', function($scope, $filter){
    $scope.oreGen = '<div class="oreFunction" ng-click="collectFunction(\'parenthesis\', 1)">test text</div>';
    $scope.collectFunction = function(value1, value2){
      alert(value1 + value2);
    };
  }]);

angular.module('programApp.filters', []).filter('trust', ['$sce', function($sce){
  return function(text) {
    return $sce.trustAsHtml(text);
  };
}]);

加载页面时,主元素内没有任何内容。

这是一个代码笔:http://codepen.io/trueScript/pen/MwbVpO?editors=101

可以看到被 ngBinded 的 div 没有出现。 这是为什么?

【问题讨论】:

  • 你的html codepen中的ng-app在哪里。看起来你错过了它。如果它成功了,那么它不会触发ng-click事件,因为ng-bind-html不会为你编译元素..

标签: javascript angularjs ng-bind-html ng-bind ngsanitize


【解决方案1】:

您可以使用指令代替过滤器。请看这个JSFiddle

HTML:

<div ng-app="myApp" ng-controller="programController">
    <dir id="main" content="oreGen"></dir>
</div>

JS:

angular.module('myApp', [])
.controller('programController', ['$scope', '$filter', function ($scope, $filter) {
    $scope.oreGen = '<dir class="oreFunction" ng-click="collectFunction(\'parenthesis\', 1)">test text</dir>';
    $scope.collectFunction = function (value1, value2) {
        alert(value1 + value2);
    };
}])
.directive('dir', function ($compile, $parse) {
    return {
        restrict: 'E',
        link: function (scope, element, attr) {
            scope.$watch(attr.content, function () {
                element.html($parse(attr.content)(scope));
                $compile(element.contents())(scope);
            }, true);
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2014-10-31
    相关资源
    最近更新 更多