Javascript AngularJS:'$scope 未定义'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29385648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: '$scope is not defined'
提问by tonejac
I keep getting '$scope is not defined' console errors for this controller code in AngularJS:
对于 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;
});
};
Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
我应该在我的 AngularJS MVC 文件中的哪个位置查找 $scope 未正确定义的问题?
回答by Rhono
For others who land here from Google, you'll get this error if you forget the quotes around $scopewhen you're annotating the function for minification.
对于从 Google 登陆这里的其他人,如果$scope您在注释函数以进行缩小时忘记了引号,您将收到此错误。
Error
错误
app.controller('myCtrl', [$scope, function($scope) {
...
}]);
Happy Angular
快乐角
app.controller('myCtrl', ['$scope', function($scope) {
...
}]);
回答by squiroid
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;
});
};
}
]);
回答by Hornth
Just put you $scope.create function inside your controller. Not outside !
只需将 $scope.create 函数放在控制器中即可。不在外面!
$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.
$scope 仅在控制器中定义,每个控制器都有自己的。所以在你的控制器之外写 $scope 是行不通的。
回答by yasin
Check scope variable declared after controller defined. Eg:
检查定义控制器后声明的范围变量。例如:
var app = angular.module('myApp','');
app.controller('customersCtrl', function($scope, $http) {
//define scope variable here.
});
Check defined range of controller in view page.
检查视图页面中定义的控制器范围。
Eg:
例如:
<div ng-controller="mycontroller">
//scope variable used inside these blocks
<div>

