AngularJS: '$scope 未定义'

AngularJS: '$scope is not defined'

我在 AngularJS:

中不断收到此控制器代码的“$scope is not defined”控制台错误
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;
    });
};

我应该查看 AngularJS MVC 文件中的哪个位置以发现 $scope 未正确定义的问题?

将该代码放入控制器中:-

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

只需将 $scope.create 函数放入控制器中即可。不在外面!

$scope只定义在控制器中,每个控制器都有自己的。所以在你的控制器之外写 $scope 是行不通的。

对于从 Google 登陆这里的其他人,如果您在注释函数以进行缩小时忘记了 $scope 周围的引号,就会出现此错误。

错误

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

快乐Angular

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

检查定义控制器后声明的范围变量。 例如:

    var app = angular.module('myApp','');
     app.controller('customersCtrl', function($scope, $http) {
     //define scope variable here.

});

查看视图页面中定义的控制器范围。

例如:

<div ng-controller="mycontroller">
//scope variable used inside these blocks

<div>