Ng-click不以angularjs中触发

Ng-click not firing in angularjs?

本文关键字:angularjs 不以 Ng-click      更新时间:2023-09-26

在这里,我创建了用于按钮单击的示例角度程序。 但它没有发射我可以知道我哪里做错了吗?任何人都可以帮我解决这个问题..谢谢

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $sce) {
    $scope.buttonHtml = $sce.trustAsHtml("<button ng-click='showMessage('"foo'")'>click me</button>");
    $scope.showMessage = function(message) {
        alert(message);
    }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <div ng-bind-html="buttonHtml"></div>
</div>

问题是,即使 html 呈现得很好,Angular 实际上也没有将ng-click绑定到scope,要做到这一点,你必须先$compile它。

var compiledHtml = $compile("<button ng-click='showMessage('"foo'")'>click me</button>")($scope);

您需要编译并将元素与正确的范围链接,并替换"旧元素"。这应该通过指令来完成:

.HTML:

<div ng-app="myApp" ng-controller="MyCtrl">
  <div replace-with-compiled-html="buttonHtml"></div>
</div>

.JS:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
  $scope.buttonHtml = "<button ng-click='showMessage('"foo'")'>click me</button>";
  $scope.showMessage = function(message) {
    alert(message);
  }
});
myApp.directive('replaceWithCompiledHtml', function($compile) {
  return {
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        post: function preLink(scope, elem, iAttrs, controller) {
          // use the inherited scope -> get the wanted property via the attributes
          var scopePropName = iAttrs['replaceWithCompiledHtml'];
          // compile the html
          var linkingFunc = $compile(scope[scopePropName]);
          // link it with the correct inherited scope
          linkingFunc(scope, function(newElem) {
            // replace the new compiled element with the previous one
            elem.replaceWith(newElem);
          });
        }
      };
    }
  }
});

吉斯菲德尔。