【问题标题】:ng-click not working inside the controller using of ng-bind-html使用 ng-bind-html 的 ng-click 在控制器内部不起作用
【发布时间】:2015-10-27 19:26:13
【问题描述】:

在我的代码下方 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>

【问题讨论】:

    标签: javascript angularjs html angularjs-controller ng-bind-html


    【解决方案1】:

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

    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>
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        问题是 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 引用为&lt;div compile="firstName"&gt;&lt;div&gt;

        【讨论】:

          【解决方案4】:

          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
          

          【讨论】:

          • @NelsonA 很高兴为您提供帮助..谢谢 :)