Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: '$scope is not defined'

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?

like image 433
tonejac Avatar asked Apr 01 '15 07:04

tonejac


People also ask

What is scope in AngularJS?

The Scope in AngularJS is the binding part between HTML (view) and JavaScript (controller) and it is a built-in object. It contains application data and objects. It is available for both the view and the controller. It is an object with available properties and methods. There are two types of scopes in Angular JS.

Does AngularJS support scope inheritance?

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes.

How do you access $scope in console?

scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .


2 Answers

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) {
  ...
}]);
like image 103
rhinosforhire Avatar answered Sep 27 '22 23:09

rhinosforhire


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;
    });
};
        }
    ]);
like image 45
squiroid Avatar answered Sep 28 '22 00:09

squiroid