虽然不建议您访问工厂和服务中的$ scope,但您可以使用 angular.element(ELEMENT).scope() 。
angular.element(ELEMENT).scope()
但是最好让您的身份验证服务接受用户名和密码,并假设其当前范围不能使其可重用:
authenticateUser: function (username, password) { ...... // return result.then(successCall, errorCall); // return the promise }
然后在你的控制器中:
$scope.ValidateLogin = function () { ....// authenticationService.authenticateUser($scope.username, $scope.password) .then(function(response){ // deal with the response here }); }
您的服务中存在吊装问题:
'use strict'; app.factory('authenticationService', ['$scope', 'httpService', function ($scope, httpService) { //define them here before the return, if not, they won't be defined var successCall =function(dataObject) { } var errorCall = function (dataObject) { } return { authenticateUser: function () { if (!$scope.userName && !$scope.keyWord) { var result = httpService.postService( { username: $scope.userName, keyword: $scope.keyWord }, "../api/authenticateUser"); result.then(successCall, errorCall); } } } }]);
这里的基本问题是你的工厂没有正确初始化。 工厂定义不正确,因为您正在使用 $scope 。 $scope 不是服务而是对象。 $scope 对象绑定到一些html元素/上下文。我们可以用 $scope 使用控制器作为Injector初始化控制器 $scope 在解析html元素时。控制器与html元素相关联,因此Injector知道 $scope 为控制器。 但服务/工厂是单件对象。所以你不能注射 $scope 这里。
$scope
有关其他说明,请参阅 将$ scope注入角度服务函数()
使用以下代码可以解决您的问题。我假设你已经定义了 httpsService 。
httpsService
app.factory('authenticationService', ['httpService', function (httpService) { return { authenticateUser: function (context) { if (!context.userName && !context.keyWord) { var result = httpService.postService( { username: context.userName, keyword: context.keyWord }, "../api/authenticateUser"); result.then(successCall, errorCall); } } } app.controller('LoginController', ['$scope','authenticationService', function ($scope, authenticationService) { $scope.ValidateLogin = function () { var result = window.confirm("Validate Login Called for the user :" + $scope.userName); var result1 = authenticationService.authenticateUser($scope); } }]);