AngularJS如何在函数外部正确调用函数

时间:2016-08-10 22:00:25

标签: javascript html angularjs

我是AngularJS的新手,我正在尝试编写代码以从JSON文件中提取数据。 我写了一个GET函数,现在想在函数之外调用GET函数。

我有一个getData函数,在最后一行有var questions = getData'~~~'。我认为这在我的代码中是错误的。如何调用getData函数的DataFactory函数。

(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');
})();

2 个答案:

答案 0 :(得分:0)

您需要在“工厂”或“服务”文件中进行api调用。然后拨打电话     'Controller'文件中Factory文件中的'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);
                }
            );
        }
    }
})();

答案 1 :(得分: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/