角度指令中的范围问题

时间:2013-10-02 14:12:25

标签: angularjs

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

http://jsfiddle.net/9q6MG/

控制台(鼠标悬停在闪光灯上)

Expected: 'speed'    
Actual: []    

http://jsfiddle.net/ewmCT/

1 个答案:

答案 0 :(得分: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

相关问题