【问题标题】:How to access the scope properties of nested Angular directives如何访问嵌套 Angular 指令的范围属性
【发布时间】:2015-08-28 03:12:10
【问题描述】:

我在访问 Angular 中的内部指令范围时遇到问题。

我创建了两个指令,一个内部指令和一个外部指令。我希望他们都有隔离范围。我希望内部指令成为表单标签上的一个属性,并且我希望在提交表单时调用内部指令范围内的函数。

不幸的是,我似乎无法让它工作。

为什么我不能访问内部指令的 doThing 函数?此外,如果我将 innerDirective 更改为 scope: false,我将无法访问外部指令的 doSomething 函数。我不确定我在这里缺少什么。

http://codepen.io/justinbc820/pen/vNBWMp

angular.module('app', [])
.directive('outerDirective', function() {
    return {
        restrict: 'E',
        scope: {},
        link: function(scope) {
            scope.doThing = function() {
              alert('outer directive');
            }
        }
    };
})
.directive('innerDirective', function() {
    return {
        restrict: 'A',
        scope: {},
        link: function(scope, element) {
            scope.doThing = function() {
                alert('inner directive');
            }
        }
    };
});


<div ng-app="app">
  <outer-directive>

    <form inner-directive ng-submit="doThing()">
      <button type="submit">Do THING</button>
    </form>

  </outer-directive>
</div>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    您可以在 innerDirective 中使用 scope.$parent,如下所示。

    .directive('innerDirective', function() {
        return {
            restrict: 'A',
            scope: {},
            link: function(scope, element) {
            scope.$parent.doThing = function() {
              alert('inner directive');          
            }
           }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      相关资源
      最近更新 更多