ACIDSTEALTH February 2016

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

Answers


Alon Eitan February 2016

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


migg February 2016

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


Rahul Tagore February 2016

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.


Steven Wexler February 2016

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.
};

Post Status

Asked in February 2016
Viewed 3,974 times
Voted 14
Answered 4 times

Search




Leave an answer