AngularJS - $ emit只能在它的当前范围内运行吗?

时间:2014-01-28 10:16:53

标签: javascript angularjs

我创建了2个指令:Parent和Child。试图让他们互相交谈。看起来如果他们都有范围他们没有收到事件。根据{{​​1}}声明$emit

的文档,这似乎不正确

当然,应该通过范围冒泡?

http://plnkr.co/edit/WNqN4XZKaLAvBEtSyERA?p=preview

2 个答案:

答案 0 :(得分:6)

问题在于父/子假设:

  • 只是儿童的父元素,但不是父范围。
  • 实际上他们是兄弟范围,在这种情况下, $ rootScope $ id:002 )的两个孩子。

为什么?

  • 由于this commitIsolate scope is now available only to the isolate directive that requested it and its template
  • 这意味着父指令内容(包括子指令)仍然链接到外部范围。
  • 因此子指令创建了隔离范围,它是外部范围的子节点。
  • $ emit $ broadcast 都不适用于兄弟范围。

enter image description here


解决方案:

这是一个吸虫:http://plnkr.co/edit/EfKJthkQLitWnF2srykM?p=preview

您可以将子指令创建为父指令的模板,因为模板指令确实获得了如上所述的指令范围。

.directive('parent', function ($timeout) {
  return {
    template:'<child name="Jimmy"></child>',

你真的需要活动巴士吗?

另一个解决方案是在父指令上创建一个控制器,并在子指令中要求它。

.directive('parent', function ($timeout) {
  return {
    controller: function(){
      this.hungry = function(message){
        // something
      }
    }

儿童指令:

.directive('child', function ($timeout) {
  return {
    require: "^parent",
    link: function (scope, element, attrs, parentCtrl) {

       parentCtrl.hungry("I'm hungry!")

答案 1 :(得分:1)

在您的示例中,两个指令都具有来自同一父作用域的隔离范围,因此它们没有父/子关系。

为了让它按预期运作,您可以指定scope: true而不是scope: {...}。在这种情况下,child指令的范围将是父指令范围的子范围。

see the plucker

相关问题