简体   繁体   中英

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> 

This code will solve your issue. add this directive in 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 be like this:

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

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

The issue is Angular won't parse the directives inside your ng-bind-html .

A proper solution to this is creating a directive yourself to compile the html you 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 reference firstName as <div compile="firstName"><div>

Try this ... this link solve my problem code : Link code
Add directive

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM