0

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

<!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>

Plunker:http ://plnkr.co/edit/Sm81SzfdlTrziTismOg6

4

1 回答 1

4

它不起作用,因为您在不同的范围内使用了 2 个指令,ngClick并且myScopedDirective. 您需要为您的指令创建一个模板并调用 click 函数,如下所示:

<!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>

工作的笨蛋

于 2015-07-08T23:52:09.913 回答