AngularJS:'$范围未定义'

AngularJS: '$scope is not defined'

本文关键字:未定义 范围 AngularJS      更新时间:2023-09-26

我在AngularJS:中不断收到此控制器代码的"$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;
    });
};

在我的AngularJS MVC文件中,我应该在哪里查找$scope定义不正确的问题?

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

错误

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

Happy Angular

app.controller('myCtrl', ['$scope', function($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是不起作用的。

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

    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>