Dan Tang
Dan Tang

Reputation: 1343

Scope problems within angular directives

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/

Upvotes: 0

Views: 131

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

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

Upvotes: 3

Related Questions