【问题标题】:Send callback to non isolated scope child向非隔离作用域子发送回调
【发布时间】:2017-10-13 19:25:20
【问题描述】:

我需要为子指令添加回调,这不是一个孤立的范围。我知道你可以用一个独立的范围来做到这一点,你也可以使用 scope.$parent 来访问它,但是如果直接父级是错误的父级,这并不总是正确的。

myApp.directive('parentDirective', function() {
  return {
    link: function(scope) {
      scope.callback = function(msg) {
       alert(msg);
      }
    }
  }
});

myApp.directive('childDirective', function() {
  return {
    scope: true,
    link: function(scope, element, attrs) {
      var msg = 'from child';
      if (angular.isDefined(attrs.callback)) {
         scope.$parent.$apply(attr.callback);
      }
    }
  }
});

这可行,但我不喜欢它,我讨厌必须手动触发 $apply 或 $digest,也讨厌更多地尝试访问 scope.$parent,因为这并不总是预期的范围...

有没有更好的解决方案?

【问题讨论】:

  • 我所做的只是删除了Angular 标签,因为它适用于 Angular >= 2.0.0,而您的问题显然是关于 Angularjs 1.x.x 的。我也没有发布答案。有成千上万的人在观看 Angular 标签,不仅是我 ;-)

标签: angularjs binding callback angularjs-scope


【解决方案1】:

问题是隔离作用域在原型上并不继承,如果您需要从隔离作用域解析为子指令(嵌套),则需要手动转入内容并将隔离作用域用作上下文。

var myApp = angular.module('myApp', [])
  .directive('myWrapperDirective', function() {
    return {
      scope: {},
      transclude: true,
      link: function($scope, $element, $attrs, $null, $transclude) {
        $scope.name= 'test';
        $transclude($scope, function(clone) {
          $element.append(clone);
        });
      }
    }
  })
  .directive('myNestedDirective', function() {
    return {
      scope: true,
      link: function($scope, $element, $attrs) {
        // now child directive and parent share same scope.
        console.log($scope.name);
      }
    };
  });

模板:

<div my-wrapper-directive>
  Hello, {{name}}!
  <div my-nested-directive>
    {{name}}
  </div>
</div>

演示:http://jsfiddle.net/xM92P/786/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多