0

I'm following the lessons on egghead.io (http://egghead.io/lessons/angularjs-directive-to-directive-communication), and I'm having some scope problems. When I mouse over <superhero flash>flash</superhero>, I am getting a blank array instead of 'speed'. However, when I add the flash directive to the second superhero directive, it prints it correctly. I am wondering if there are any scope problems I am having?

http://jsfiddle.net/9q6MG/

Console (on mouse over on flash)

Expected: 'speed'    
Actual: []    

http://jsfiddle.net/ewmCT/

1 Answer 1

3

The problem is because of the shared scope used by the superhero directive.

The superhero directive uses the parent elements scope as its own scope because you are not using child/isolated scopes for the directive. There for both the superhero elements in your sample shares the same scope.

So first superhero creates a empty array property abilities and since it has a speed directive adds speed to it, then when the second superhero element is compiled and processed it overrides this property again with a empty array because both of them works in the same scope

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

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Just to check - does this mean that each directive has an individual scope?
@DanTang once you have define scope:true the element with the directive will have a individual scope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.