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

徘徊边缘 提交于 2019-12-07 08:55:14

问题


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>

回答1:


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



回答2:


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>



回答3:


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>




回答4:


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

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


来源:https://stackoverflow.com/questions/31825405/ng-click-not-working-inside-the-controller-using-of-ng-bind-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!