如何在 angular 中使范围函数可用于已编译的模板

How to make scope functions available to compiled template in angular

我正在尝试编写一个服务,它将编译 HTML 指令并将其附加到 body 元素。当指令处理文本时,函数不是。

这是一个更简单的版本,我无法对 ng-click 指令执行相同的操作并从控制器对其进行编译。谁能告诉我如何实现这一目标。我的目标是创建一个非常基本的指令,其功能类似于 angular ui-bootstrap 的模式或 Angular material.

的对话框服务

angular
  .module('app', [])
  .controller('ctrl', ctrl);

function ctrl($scope, $compile) {
  var html = '',
    newScope = $scope.$new(true),
    newScope1 = $scope.$new(true);

  $scope.text = 'from controller';
  $scope.fun = function() {
    alert('from controller');
  };
  newScope.text = 'from controller with new scope';
  newScope.fun = function() {
    alert('from controller with new scope');
  };
  newScope1.text = 'from controller with new scope1';
  newScope1.fun = function() {
    alert('from controller with new scope1');
  };

  html = $compile('<button ng-click="fun">{{text}}</button>')($scope);
  angular.element('body').append(html);

  html = $compile('<button ng-click="fun">{{text}}</button>')(newScope);
  angular.element('body').append(html);

  $compile('<button ng-click="fun">{{text}}</button>')(newScope1, function(clonedElement, scope) {
    console.log(clonedElement, scope);
    angular.element('body').append(clonedElement);
  });
}
<!DOCTYPE html>
<html>

<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="app" ng-controller="ctrl">
  <h1>Hello Plunker!</h1>
</body>

</html>

plunkr

你做得对,只需调用方法使用 ng-click="fun()" 而不是 ng-click="fun"(唯一缺少的东西)

html = $compile('<button ng-click="fun()">{{text}}</button>')(newScope);