使用ng-bind-html时,Ng-click不能在控制器内部工作

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

本文关键字:控制器 内部 工作 不能 Ng-click ng-bind-html 使用      更新时间:2023-09-26

下面我的代码ng-click不工作,而我正在检查检查元素ng-click不显示,帮助我如何做

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>

这段代码将解决您的问题。在你的控制器中添加这个指令。

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
                });
            }
        }
    })

,你的HTML将像这样:

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

你的ng-click不工作的原因是因为,ng-bind-html不编译div,你应该使用ng-if那里编译一个div并添加元素从指令而不是控制器。

标记

<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>

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

问题是Angular不会解析ng-bind-html中的指令。

一个正确的解决方案是自己创建一个指令来编译你包含的html

.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);
        }
    );
  };
}])

则可以将firstName引用为<div compile="firstName"><div>

试试这个…这个链接解决了我的问题code:链接代码
添加指令

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