我正在尝试创建角度服务,但它无法正常工作。我已经尝试了numeros的东西,并查看了一切。请帮助
//service
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin()
{
this.testFunc = function ()
{
console.log("THIS IS A TEST SERVICE");
}
};
下面:尝试调用服务测试函数
//controller
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope','$rootScope','$http','googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc(); // this doesnt work, error: "main.min.js:2 Error: [$injector:undef] http://errors.angularjs.org/1.5.8/$injector/undef?p0=googleLogin"
我觉得问题是注射我只是不知道在哪里。请帮助谢谢
答案 0 :(得分:3)
工厂需要返回函数引用,你需要声明变量testFunc
(回答为什么here):
更新工作代码段。
angular.module('RDash', []);
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc : testFunc
}
};
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope', '$rootScope', '$http', 'googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc();
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="RDash" ng-controller="ComposeCtrl"></div>
&#13;
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc: testFunc
}
};
&#13;