通过$ sce.trustAsHtml呈现时访问ng-click

时间:2017-01-22 04:50:37

标签: angularjs

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

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

我使用$ sce.trustAsHtml渲染$ scope.content

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

2 个答案:

答案 0 :(得分:2)

上面的代码确实被编译了,但是由于角标记js将其锚定为不安全,因此ng-click不起作用。

您可以通过francis bouvier使用https://example.com/chat/54554/77d4d7d7 -> https://example.com/webrtcchat/54554/77d4d7d7 代替https://example.com/var/www/example.com/webrtcchat/ 来实现您想要达到的目标。它是我见过的最薄的库,只有1kb。 https://github.com/francisbouvier/ng_html_compile

也请参考https://stackoverflow.com/a/41790235

答案 1 :(得分:0)

因为它不是$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);
        }
    );
  };
}]);