2016-08-10 2 views
1

저는 AngularJS를 처음 사용하며 JSON 파일에서 데이터를 추출하는 코드를 작성하려고합니다. GET 함수를 작성 했으므로 이제는 함수 외부에서 GET 함수를 호출하려고합니다.AngularJS 함수 외부에서 함수를 올바르게 호출 할 수있는 방법은 무엇입니까?

나는 getData 기능을 가지고 있으며 마지막 줄에는 var questions = getData'~~~'이 있습니다. 나는 이것이 내 코드에서 잘못되었다고 생각한다. DataFactory 함수 밖에서 getData 함수를 호출하려면 어떻게해야합니까?

(function(){ 
angular 
    .module("GrammarQuiz") 
    .factory("DataService", DataFactory); 

    function DataFactory($log, $http){ 
     var vm = this 
     var dataObj = { 
     questions: questions 
     }; 
     vm.sort = sort; 
     vm.random = random; 
     vm.getData = getData; 
     var temp = 0; 

     // right now I have questions variable here 
     // but I want to move this to the outside of the function 
     //var questions = getData('data1.json'); 

     function getData(apicall){ 
      $log.log('begin!!!'); 
      $http.get('api/' + apicall, 
        {headers: 
         {token: 'check!'} 
        } 
      ).then(function(response){ 
       $log.log(response.data);  
       questions = response.data; 
       }, function(response){ 
        $log.log(response.data || "Request failed"); 
       }); 
     } 
     function sort(array) { 
      return array.sort(function() { 
      return .5 - Math.random(); 
      }); 
     } 
     function random() { 
      for (var key in dataObj.questions) { 
      dataObj.questions[key].Choices = sort(dataObj.questions[key].Choices); 
      } 
     } 
     random(); 
     return dataObj; 
    } 

    var questions = DataFactory.getData('data1.json'); 
})(); 
+0

당신은 (예를 들어, 컨트롤러)이 팩토리를 주입해야합니다. 그런 다음 getData 메소드에 액세스 할 수 있습니다. –

답변

0

나는 내 댓글에서 언급 한 바와 같이, 당신은 당신의 컨트롤러에 서비스를 주입 할 필요가있다. 이런 식으로 뭔가 작동 :

(function(){ 
    var myApp = angular.module('myApp',[]); 

    angular 
    .module("myApp") 
    .controller("MyCtrl", MyCtrl); 

    MyCtrl.$inject = ["myApp.myService"]; //injects your service into your controller 

    function MyCtrl(dataservice) { 
     var vm = this; 
     vm.name = 'Superhero'; 
     //calls the service 
     dataservice.getData(); 
    } 

    angular.module("myApp").factory("myApp.myService", function() { 
     //exposes the service's methods 
     //you need this, vs the vm syntax in your service 
      var service = { 
      getData: getData 
     }; 

     return service; 

    function getData(){ 
     alert("S"); 
    } 
    }); 
})(); 

JSFiddle : http://jsfiddle.net/Lvc0u55v/8234/

0

'공장'또는 '서비스'파일에서 API 호출을해야합니다. 그런 다음 '컨트롤러'파일의 팩토리 파일에서 'get'메소드를 호출하십시오. 코드 분리가 필요하므로 은 공장 및 컨트롤러를 이용합니다.

아래의 예를 참조하십시오

# user.factory.js 
# 'app.foo.user' refers to your directory structure i.e. app/foo/user/user.factory.js 

(function() { 
    'use strict'; 

    angular 
     .module('app.foo.user', []) 
     .factory('userSvc', UserService); 

    /* @ngInject */ 
    function UserService(
     $log, 
     $q, 
     $http, 
     $window, 
     $state, 
     logger, 
     session, 
     utils, 
     API_CONFIG) { 

     var ENDPOINTS = { 
      USERS: '/v1/users' 
     }; 

     /** 
     * @ngdoc service 
     * @name app.foo.user 
     * @description User management 
     */ 
     var service = { 
      get: get 
     }; 

     /** 
     * @ngdoc method 
     * @name get 
     * @description Returns all users 
     * @methodOf app.foo.user 
     * @returms {promise} user or null if not found 
     */ 
     function get() { 
      var q = $q.defer(); 

      var request = utils.buildAuthRequest(session, 'GET', ENDPOINTS.USERS); 

      $http(request) 
       .success(function (users) { 
        q.resolve(users.result); 
       }) 
       .error(function (error) { 
        logger.error('UserService.get > Error ', error); 

      return q.promise; 
     } 
    } 
})(); 

//------------------------------------------------------------------------------------ 
# user.module.js 
# 'app.foo.user' refers to your directory structure i.e. app/foo/user/user.module.js 

(function() { 
    'use strict'; 

    angular 
     .module('app.foo.user', [ 
     ]); 
})(); 

//------------------------------------------------------------------------------------ 
# user-list.controller.js 
# This is where you make a call to the 'get' method in the 'user.factory.js'. 
# And you gave to inject 'userSvc' in this file so as to connect to the 'user.factory.js' file. 
# 'app.foo.admin' refers to your directory structure i.e. app/foo/admin/user-list.controller.js 

(function() { 
    'use strict'; 

    angular 
     .module('app.foo.admin') 
     .controller('UsersListController', UsersListController); 

    /* @ngInject */ 

    function UsersListController(
     $scope, 
     $state, 
     $timeout, 
     $log, 
     userSvc) { 
     var vm = this; 
     vm.loading = false; 
     vm.userSvc = userSvc; 

     activate(); 

     function activate() { 
      // init users 
      vm.userSvc.get().then(
       function(users) { 
        initSearchString(users); 

        vm.users = users; 
       }, 
       function(error) { 
        $log.error(error); 
       } 
      ); 
     } 
    } 
})(); 
관련 문제