2013-10-02 28 views
0

我正在关注egghead.io(http://egghead.io/lessons/angularjs-directive-to-directive-communication)上的课程,我遇到了一些示波器问题。当我将鼠标移过<superhero flash>flash</superhero>时,我得到一个空白数组而不是'速度'。但是,当我将flash指令添加到第二个超级英雄指令时,它会正确打印它。我想知道我是否有任何范围问题?角度指令中的示波器问题

http://jsfiddle.net/9q6MG/

控制台(关于闪光灯鼠标)

Expected: 'speed'  
Actual: []  

http://jsfiddle.net/ewmCT/

回答

3

的问题是,因为由超级英雄指令使用的共享范围。

superhero指令使用父元素作用域作为它自己的作用域,因为您没有为指令使用子/隔离作用域。对于你的样本中的两个超级英雄元素都有相同的范围。

所以第一个超级英雄创建一个空数组属性abilities并且因为它有一个speed指令增加了speed它,那么当第二个超级英雄元素被编译并处理它再次重写这个属性与空数组,因为他们都在工作同一范围

var app = angular.module('myApp', []); 
app.directive('superhero', function() { 
    return { 
     restrict: 'E', 
     scope: true, 
     controller: function ($scope) { 
      $scope.abilities = []; 

      this.addStrength = function() { 
       console.log('adding strength', $scope.$id); 
       $scope.abilities.push('strength'); 
       console.log($scope.abilities); 
      } 

      this.addSpeed = function() { 
       console.log('adding speed', $scope.$id); 
       $scope.abilities.push('speed'); 
       console.log($scope.abilities); 
      } 
     }, 
     link: function (scope, element) { 
      console.log('link', scope.$id, scope.abilities) 
      element.bind('mouseenter', function() { 
       console.log('me', scope.$id, scope.abilities) 
      }) 
     } 
    } 
}) 

演示:Fiddle

+0

谢谢你,完美的作品 –

+0

只是为了检查 - 这是否意味着每个指令有一个单独的范围是什么? –

+1

@DanTang一旦你定义了'scope:true',指令中的元素将有一个单独的范围 –