Daniel Bonnell
Daniel Bonnell

Reputation: 4997

AngularJS Directive $scope is undefined

I have the following directive. When I trigger the open function and get to the debugger I get an error message in the console that says Uncaught ReferenceError: $scope is not defined(…).

How is it possible for $scope.open to be called when $scope is undefined?

app.directive('photo', ['$http', 'modal', function($http, modal) {
    return {
        replace: true,
        templateUrl: '/assets/photo.html',
        transclude: false,
        scope: {
            result: '=',
            index: '@'
        },
        controller: ['$scope', '$http', 'modal', function($scope, $http, modal) {
            $scope.prev = $scope.index - 1;
            $scope.open = function() {
                debugger;
            };
        }]
    }
}]);

Here is my DOM:

<div ng-repeat="r in results" photo result="r" index="$index"></div>

If I insert console.log($scope) just before my open function, and then again right before the debugger in that function, I get the following results. Left is before open is called, right is after open is called. enter image description here

Upvotes: 1

Views: 2997

Answers (5)

mesutpiskin
mesutpiskin

Reputation: 1937

its worked for me

var app = angular.module("moduleTest",[]);
app.directive("testDirective",function(){
    return {
        restrict: "A",
        scope: true,
        link: function(scope, element){
           //code
           //and $scope is scope
        }
    }   
 });

Upvotes: 1

Steven Wexler
Steven Wexler

Reputation: 17329

Try adding a statement that uses $scope in $scope.open. Chrome has probably optimized $scope away when you're in $scope.open because you're not using it.

$scope.open = function() {
  console.log($scope);
  debugger; //now you should see $scope.
};

Upvotes: 1

Rahul Tagore
Rahul Tagore

Reputation: 101

You need to define the $Scope at the top i.e.:
app.directive('photo', ['$http', '$Scope','modal', function($http, $Scope, modal)

It will work fine now.

Upvotes: 0

crackmigg
crackmigg

Reputation: 5901

This should work:

app.directive('photo', ['$http', 'modal', function($http, modal) {
return {
    replace: true,
    templateUrl: '/assets/photo.html',
    transclude: false,
    scope: {
        result: '=',
        index: '@'
    },
    controller: function($scope, $http, modal) {
        $scope.prev = $scope.index - 1;
        $scope.open = function() {
            debugger;
        };
    }
}
}]);

Upvotes: 0

Alon Eitan
Alon Eitan

Reputation: 12025

You inject the $http and modal in the directive definition (as you did), no need to in the controller function, just do:

controller: function($scope) {
        $scope.prev = $scope.index - 1;
        $scope.open = function() {
            debugger;
        };
    }

Upvotes: 3

Related Questions