Angular 指令隔离作用域:作用域函数不会执行

Angular directive isolate scope: scope function won't execute

我无法理解如何定义由具有独立范围的指令(或指令内部)使用的函数。在下面的代码中,为什么 $scope.foo() 函数没有执行?有没有正确的方法可以解决这个问题?我希望制作一个仅在用户登录时才可见的按钮,并且认为指令是 encapsulate/isolate 该功能的好方法。

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.angularjs.org/1.4.2/angular.js"></script>
  <script>
    angular.module('MyApp', [])
      .directive('myScopedDirective', function() {
        return {
          scope: {}, // <!-- isolate scope breaks things
          controller: function($scope) {
            // isolate scope prevents this function from being executed
            $scope.foo = function() {
              alert('myScopedDirective / foo()');
            };
          }
        };
      });
  </script>
</head>

<body>
  <div ng-app="MyApp">
    <!-- button doesn't work unless isolate scope is removed -->
    <button my-scoped-directive ng-click="foo()">directive container - foo()</button>
  </div>
</body>

</html>

笨蛋:http://plnkr.co/edit/Sm81SzfdlTrziTismOg6

它不起作用,因为您在不同的范围内使用了 2 个指令,ngClickmyScopedDirective。您需要为您的指令创建一个模板并像这样调用点击函数:

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.angularjs.org/1.4.2/angular.js"></script>
  <script>
    angular.module('MyApp', [])
      .directive('myScopedDirective', function() {
        return {
          restrict: 'AE', // Can be defined as element or attribute
          scope: {},
          // Call the click function from your directive template
          template: '<button ng-click="foo()">directive container - foo()</button>',
          controller: function($scope) {
            $scope.foo = function() {
              alert('myDirective / foo()');
            };
          }
        };
      });
  </script>
</head>

<body>
  <div ng-app="MyApp">
    <my-scoped-directive></my-scoped-directive>
  </div>
</body>

</html>

工作plunker