Angular指令隔离scope: scope函数won't execute

Angular directive isolate scope: scope function won't execute

本文关键字:scope execute 函数 指令 隔离 Angular won      更新时间:2023-09-26

我很难理解如何定义由(或内部)具有隔离作用域的指令使用的函数。在下面的代码中,为什么$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>

砰砰作响:http://plnkr.co/edit/Sm81SzfdlTrziTismOg6

它不工作,因为你在不同的范围内使用2个指令,ngClickmyScopedDirective。你需要为指令创建一个模板,并像这样调用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>
工作恰好