0

I've got a simple angular app, and I'm trying to inject some html into the page using ngBindHtml. However, it's not being injected. Here's my HTML:

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

And here's my angular app:

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);
  };
}]);

When the page is loaded, nothing appears inside the main element.

Here's a codepen: http://codepen.io/trueScript/pen/MwbVpO?editors=101

You can see the div being ngBinded does not appear. Why is this?

alloy
  • 756
  • 1
  • 13
  • 23
  • 1
    where is `ng-app` in your html codepen.. looks like you missed it.. If it got work then it will not fire `ng-click` event as `ng-bind-html` doesn't compile element for you.. – Pankaj Parkar Jul 23 '15 at 15:35

1 Answers1

0

You can use a directive instead a filter. Please look at this 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);
        }
    }
});
michelem
  • 14,430
  • 5
  • 50
  • 66