AngularJS: '$scope is not defined'

49,586

Solution 1

Place that code inside controller:-

angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
        function($scope, $routeParams, $location, Authentication, Articles){
            $scope.authentication = Authentication;

$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
    var article = new Articles({
        title: this.title,
        content: this.content
    });

    article.$save(function(response) {
        $location.path('articles/' + response._id);
    }, function(errorResponse) {
        $scope.error = errorResponse.data.message;
    });
};
        }
    ]);

Solution 2

For others who land here from Google, you'll get this error if you forget the quotes around $scope when you're annotating the function for minification.

Error

app.controller('myCtrl', [$scope, function($scope) {
  ...
}]);

Happy Angular

app.controller('myCtrl', ['$scope', function($scope) {
  ...
}]);

Solution 3

Just put you $scope.create function inside your controller. Not outside !

$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.

Share:
49,586
tonejac
Author by

tonejac

UX and UI Designer and Developer.

Updated on August 22, 2022

Comments

  • tonejac
    tonejac over 1 year

    I keep getting '$scope is not defined' console errors for this controller code in AngularJS:

    angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
            function($scope, $routeParams, $location, Authentication, Articles){
                $scope.authentication = Authentication;
            }
        ]);
    
    
    $scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
        var article = new Articles({
            title: this.title,
            content: this.content
        });
    
        article.$save(function(response) {
            $location.path('articles/' + response._id);
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };
    

    Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?