Ng-click does not work inside the controller using ng-bind-html

below my ng-click code doesn't work while i check the ng-click validation element not showing help me how to do this

var app = angular.module('myApp', ['ngSanitize']); app.controller('myCtrl', function($scope) { $scope.firstName = "<b ng-click=test(1)>John</b><br><b ng-click=test1(1)>Testing</b>"; $scope.test=function(val) { alert(val) } $scope.test1=function(val) { alert(val) } }); 
 <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-sanitize.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <span ng-bind-html=firstName><span> </div> </body> </html> 
+4
source share
4 answers

The reason you are not working with ng-click is because the ng-bind-html doens't compile div, you have to use ng-if there OR compile the div and add this element from the directive instead of the controller.

Markup

 <div ng-app="myApp" ng-controller="myCtrl"> <span ng-if=showFirstName> <b ng-click=test(1)>John</b><br><b ng-click=test1(1)>Testing</b> <span> </div> 

the code

 $scope.showFirstName = true;//for showing div 
+2
source

This code will solve your problem. add this directive to your controller.

 directive('compileTemplate', function($compile, $parse){ return { link: function(scope, element, attr){ var parsed = $parse(attr.ngBindHtml); function getStringValue() { return (parsed(scope) || '').toString(); } //Recompile if the template changes scope.$watch(getStringValue, function() { $compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves }); } } }) 

and your HTML will look like this:

 <div id ="section1" ng-bind-html="divHtmlVariable" compile-template></div> 
+4
source

Problem Angular will not parse the directives inside your ng-bind-html .

The correct solution to this is to create a html compilation directive that you have included

 .directive('compile', ['$compile', function ($compile) { return function(scope, element, attrs) { scope.$watch( function(scope) { return scope.$eval(attrs.compile); }, function(value) { element.html(value); $compile(element.contents())(scope); } ); }; }]) 

Then you can refer to firstName as <div compile="firstName"><div>

+1
source

Try this ... this link solves my problem code: Link code
Add Directive

  myApp.directive('compile', ['$compile', function ($compile) 
0
source

All Articles