AngularJS: $scope is not defined?
AngularJS: $scope is not defined?
我已经开始学习Angular JS了,我在AngularJS中不断收到该控制器代码的控制台错误"$scope is not defined":知道吗?
服务:signup.js
'use strict';
angular.module('crud')
.service('Signup',function () {
var data={
email:$scope.email,password:$scope.password,confirmPassword:$scope.confirmPassword
}
//console.log(data);
$sails.post("/api/user",data)
.success(function (data, status, headers, jwr) {
$scope.users=data;
//$scope.user=data;
})
.error(function (data, status, headers, jwr) {
console.log(data);
//console.log(headers);
alert('Houston, we got a problem!');
});
});
Signupcontroller.js
'use strict';
angular.module('crud')
.controller('SignupCtrl', function ($scope,Signup) {
// Using .success() and .error()
});
简介
看看以下答案:https://stackoverflow.com/a/22899880/1688441
您不应该尝试从服务直接使用$scope
,因为它不可用。控制器的$scope
将包含一些变量/对象,然后可以通过调用将这些变量/对象传递给服务。
答案https://stackoverflow.com/a/22899880显示了实现您想要做的事情的正确方法,并且几乎是您基本上需要的结构(使用不同的名称)。
显然,您将需要进行更改,例如,重写他的保存方法来执行HTTP post,并联系服务器以响应登录请求。此外,由于http请求是异步的,因此最好使用resource
。请参阅:https://docs.angularjs.org/api/ngResource/service/$resource
快速粗略示例
angular.module('crud').service('SignupService', ['$http', function ($http) {
var path = '/api/user';
var loginHttpPost = function (data) {
return $http.post(path,data); //Return the promise, or instead of a service make a resource, see: https://docs.angularjs.org/api/ngResource/service/$resource
};
}])
angular.module('crud').controller('SignupCtrl', function ($scope,SignupService) {
$scope.login = function () {
var data={email:$scope.email,password:$scope.password,confirmPassword:$scope.confirmPassword};
//HTTP calls are asynchronous. Maybe better to use resource. Must use promise.
SignupService.loginHttpPost(data).success(function (data) {
//Do whatever is needed
$scope.loginResults = //assign result
}).error(function (data) {
//Do whatever is needed
$scope.loginResults = //assign result
});
};
}
]);
您没有正确注入$scope
和服务Signup
。此外,$scope
仅在控制器中可用。所以您需要将它从控制器传递给服务。
下面是正确的方法。
'use strict';
angular.module('crud')
.controller('SignupCtrl',['$scope','Signup', function ($scope,Signup) {
}]);
相关文章:
- reactRedux is not defined
- ReferenceError: not defined
- ReferenceError: cordova is not defined @ng-cordova.min.js:7
- jQuery is not defined - WordPress footer.php
- GAPI Is Not Defined
- Page_ClientValidate is not defined
- ReferenceError: $firebase is not defined
- ReferenceError: crimeID is not defined
- AngularJS: $scope is not defined?
- ajaxUrl is not defined
- WebView: Uncaught ReferenceError: Android is not defined
- ReferenceError SetInterval not defined
- ReferenceError: yes is not defined
- ReferenceError "not defined"
- Soundcloud API ReferenceError: $ is not defined (JavaScript)
- Angular: Compile is not defined
- nodeJS phantom ReferenceError: Promise is not defined
- observableArray is not defined
- Uncaught ReferenceError trapArea/Per is not defined
- ReferenceError: xmlhttp is not defined