I get a HTML-String from my database and I want to insert this into my AngularJs application via ng-bind-html
. I did it like the following:
HTML:
<div ng-bind-html="myBindHtml"></div>
JavaScript:
$scope.myBindHtml = $sce.trustAsHtml(htmlStringToInsert);
My HTML (which I want to insert) looks like this:
<button ng-click="testClickEvent()">TestButton</button>
The insert works fine.
Now I wrote an function (testClickEvent) which the button should call. This simply outputs a string into the console.
But this part does not work. I guess there is no binding from my inserted HTML to this function. Is there any way to call my function?
Angular code will only execute when you run it in the angular context. When you use ng-bind-html
its generated outside the angular context/scope, so angular events like ng-click
do not work, you need to rely on pure JS events like onclick
so refrain from these scenarios and just code them directly on angular due to complexity of solution!
We can avoid ng-bind-html
when angular events are needed and we need to directly code them in the front end and not from input from databases or other methods
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($sce, $scope) {
$scope.items = [];
for (var i = 1; i <= 2; i++) {
$scope.items.push({
description: $sce.trustAsHtml('<h2 onclick="console.log(\'hello\')">with onclick item ' + i + '</h2>')
});
};
$scope.items2 = [];
for (var i = 1; i <= 2; i++) {
$scope.items.push({
description: $sce.trustAsHtml('<h2 ng-click="console.log(\'hello\')"> with ng-click item ' + i + '</h2>')
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js" integrity="sha512-KZmyTq3PLx9EZl0RHShHQuXtrvdJ+m35tuOiwlcZfs/rE7NZv29ygNA8SFCkMXTnYZQK2OX0Gm2qKGfvWEtRXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div>
<div ng-repeat="item in items" ng-bind-html="item.description"></div>
</div>
<hr />
<div>
<div ng-repeat="item in items2" ng-bind-html="item.description"></div>
</div>
</div>
</div>