我正盯着学习angularjs(请善待)。
我正在尝试使用generatePollCode
在工厂中调用createCtrl
方法,但我收到以下消息:
Error: [$injector:undef] http://errors.angularjs.org/1.6.4/$injector/undef?p0=pollFactory...
这是我的代码:
应用初始化:
var app = angular.module("pollApp", ['ngRoute', 'ngAnimate']);
工厂:
app.factory("pollFactory", function($http){
var factory = {};
factory.generatePollCode = function(){
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ ){
text = text + possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
});
控制器:
app.controller('createCtrl', function($http, $scope, $timeout, focus, pollFactory){
$scope.submitPoll = function (){
var x =pollFactory.generatePollCode();
console.log(x);
}
});
感谢任何可以帮助我的人!
答案 0 :(得分:3)
应该是这样的。你忘记了返回工厂对象
app.factory("pollFactory", function($http){
var factory = {};
factory.generatePollCode = function(){
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ ){
text = text + possible.charAt(Math.floor(Math.random() *
possible.length));
}
return text;
};
return factory
});