AngularJS:使用ng-bind-html时无法调用onClick()

时间:2015-09-03 05:56:47

标签: angularjs

我想处理由ng-bind-html生成的onClick()事件。

我尝试了一些方法,但仍然没有找到解决方案。任何帮助都会得到满足。

<html ng-app="Demo">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script>
angular.module('Demo', [])
  .controller('MyController', ['$scope', '$sce', function($scope, $sce) {
    $scope.memo = $sce.trustAsHtml('<a href="#" ng-click="close();">Binding html</a>');
    $scope.close = function() {
      alert("close clicked");
    };
  }]);
</script>
</head>
<body ng-controller="MyController">
  <div><a href="#" ng-click="close();">No binding html</a></div> <!-- This is OK -->
  <div ng-bind-html="memo"></div> <!-- My question is here. I can't call close() -->
</body>
</html>

Upadte 1

我认为这个问题是相关的。

https://github.com/dmytrodanylyk/realm-browser

更新2

由于user2341963修复了它,但我不确定它为什么会起作用......

<html ng-app="Demo">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script>
angular.module('Demo', [])
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      link: function (scope, ele, attrs) {
        scope.$watch(attrs.dynamic, function(html) {
          ele.html(html);
          $compile(ele.contents())(scope);
        });
      }
    };
  })
  .controller('MyController', ['$scope', '$sce', function($scope, $sce) {
    $scope.memo = $sce.trustAsHtml('<a href="#" ng-click="close();">Binding html</a>');
    $scope.close = function() {
      alert("close clicked");
    };
  }]);
</script>
</head>
<body ng-controller="MyController">
  <div>
    <a href="#" ng-click="close();">No binding html</a>
  </div>
  <div dynamic="memo"></div>
</body>
</html>

0 个答案:

没有答案