AngularJS:'$ scope未定义'

时间:2015-04-01 07:59:17

标签: javascript angularjs mean-stack

我一直在' $ scope未定义' 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;
    });
};

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

4 个答案:

答案 0 :(得分:18)

对于从Google登陆的其他人,如果您在为缩小功能注释功能时忘记$scope周围的引号,则会收到此错误。

错误

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

Happy Angular

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

答案 1 :(得分:9)

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

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:0)

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

    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>