javascript - Angular Directive(指令)隔离范围 : scope function won't execute

标签 javascript angularjs angularjs-directive angularjs-scope isolate-scope

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

工作中plunker

关于javascript - Angular Directive(指令)隔离范围 : scope function won't execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305509/

相关文章:

java - Dart 将 JSON 解析成表

javascript - window.print() 在 IE\Firefox 中不显示相同的打印屏幕 HTML

javascript 替换字符串单个

javascript - Angular : Re-use controller functions and templates in different controllers

AngularJS:从不同指令读取 ngModel.$viewValue 的初始值

javascript - ionic 框架 $state.go ('app.home' );在我想去的页面上添加后退按钮(如何删除它)?

javascript - 将 $http 中的数据共享给其他 Controller 并模块化 $http 调用

javascript - 如何在单击子按钮时将 "active"类添加到 "this"父类,并在再次单击按钮时切换 "active"类

javascript - 函数(表达式)绑定(bind)不起作用

jquery - 将 AngularJS $scope 数据传递给 Jquery 元素(Stripe Checkout)