【问题标题】:Accessing ng-click when rendered via $sce.trustAsHtml通过 $sce.trustAsHtml 呈现时访问 ng-click
【发布时间】:2017-01-22 19:44:05
【问题描述】:

如何访问下面的 ng-click 功能(updateRating)?

https://jsfiddle.net/by2jax5v/171/

我正在使用 $sce.trustAsHtml 来呈现 $scope.content

$scope.bindHTML = $sce.trustAsHtml($scope.content);

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您上面的代码确实被编译了,但是考虑到锚标记不安全,它被 Angular js 清理,因此 ng-click 不起作用。

    您想要实现的目标可以通过使用 francis bouvier 的 ng-html-compile 而不是 ng-bind-html 来实现。它是我见过的最薄的库,只有 1kb。 https://github.com/francisbouvier/ng_html_compile

    也可以参考https://stackoverflow.com/a/41790235

    【讨论】:

      【解决方案2】:

      因为它不是$compiled。因此它不会告诉 Angular 搜索该 HTML 并在其中编译指令。您必须为此使用自定义指令。

      更新fiddle

      var myApp = angular.module('myApp', []);
      
      myApp.controller('MyCtrl', function($scope) {   
      
          $scope.content = "This text is <em>html capable</em> meaning you can have <a ng-click='updateRating(1)' href=\"#\">all</a> sorts <b>of</b> html in here.";
          $scope.updateRating = function(message) {
              alert(message);
          }
      
      });
      
      myApp.directive('compile', ['$compile', function ($compile) {
          return function(scope, element, attrs) {
            scope.$watch(
              function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
              },
              function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);
      
                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
              }
          );
        };
      }]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多