您好我是angularjs的新手,我正在尝试向控制器注入一些工厂,但我遇到了困难。我的工厂做得很好。我能够在工厂设置数据。
下面是我注入工厂的代码。
function () {
angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, CONSTANTS, SomeFactory) {
var OTP = $stateParams.pageList.OTP;
$scope.EnterOTP = "Please enter this OTP to verify the user " + OTP;
//RegistrationOTPVerification.$inject = ['SomeFactory'];
//Facing issues in above line
alert(1);
function RegistrationOTPVerification(SomeFactory) {
var vm = this;
vm.someVariable = SomeFactory.getData();
console.log(vm.someVariable); // logs your data
alert(vm.someVariable);
}
});
这是我的工厂代码。
(function () {
'use strict';
angular
.module('RoslpApp')
.factory('SomeFactory', SomeFactory);
SomeFactory.$inject = [];
function SomeFactory() {
var someData;
var factory = {
setData: setData,
getData: getData
};
function setData(data) {
someData = data;
}
function getData() {
return someData;
}
return factory;
}
})();
我使用SomeFactory.setData("123")
我想注入someFactory
,如下所示:
RegistrationOTPVerification.$inject = ['SomeFactory'];
但每当我写这篇文章时,我都会收到错误RegistrationOTPVerification
undefined
。如果我评论该行一切正常但我想从工厂获得一些数据。
我的工厂名称是SomeFactory
,我想注入上面的控制器。任何帮助将不胜感激。
答案 0 :(得分:2)
你错过了控制器依赖列表中的CONSTANTS:
'$translate', '$state', '$stateParams', 'SomeFactory',
... $translate, $state, $stateParams, CONSTANTS, SomeFactory) {
因此,无论您注入SomeFactory
在名称为CONSTANTS
的控制器中是否可用,且符号SomeFactory
未定义。
答案 1 :(得分:2)
首先,您在注射中错过了CONSTANTS
。
接下来,我认为你在这里混合了controller
的两种语法。使用匿名函数或命名。不要将两者混合在一起。
以下是您的代码的外观。
function () {
angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, SomeFactory) {
var vm = this;
var OTP = $stateParams.pageList.OTP;
vm.EnterOTP = "Please enter this OTP to verify the user " + OTP;
vm.someVariable = SomeFactory.getData();
console.log(vm.someVariable); // logs your data
alert(vm.someVariable);
});