0

我正在学习 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/

4

1 回答 1

3

问题是由于 superhero 指令使用的共享范围。

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)
            })
        }
    }
})

演示:小提琴

于 2013-10-02T14:23:32.083 回答