Search code examples
javascriptangularjshtmlangularjs-controllerng-bind-html

ng-click not working inside the controller using of ng-bind-html


below my code ng-click not working,while i am checking the inspect element ng-click not showing, help me how to do

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>


Solution

  • The reason behind you ng-click not working is because, ng-bind-html doens't compile div, You should use ng-if there OR compile a div and add that element from directive instead of 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>
    

    Code

    $scope.showFirstName = true;//for showing div