2017-04-08 123 views
1

嗨我是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'];

但每當我寫這篇文章,我得到錯誤RegistrationOTPVerificationundefined。如果我評論該行一切正常,但我想從工廠獲得一些數據。

我的工廠名稱是SomeFactory,我想注入上面的控制器。任何幫助,將不勝感激。

+0

分享您的工廠代碼,並提到究竟出了什麼問題 – tanmay

回答

1

首先,您在打針時錯過了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); 
}); 
2

你錯過了在控制器依賴列表常量:

'$translate', '$state', '$stateParams', 'SomeFactory', 
... $translate, $state, $stateParams, CONSTANTS, SomeFactory) { 

所以你注入SomeFactory無論是在控制器中可用的名稱CONSTANTS下和符號SomeFactory是不確定的。

+0

謝謝。 ('RoslpApp')。controller('RegistrationOTPVerification', ['$ scope','$ http','$ translatePartialLoader','$ translate','$ state','$ stateParams','CONSTANTS' ,'SomeFactory', 函數($ scope,$ http,$ translatePartialLoader,$ translate,$ state,$ stateParams,CONSTANTS,SomeFactory) –

+0

這是正確的方法嗎? –

+0

是的,這應該工作 – dfsq