简体   繁体   中英

AngularJS how can I call functions properly, outside of the function

I am new to AngularJS and am trying to write a code to extract a data from JSON file. I wrote a GET function and now want to call the GET function outside of the function.

I have a getData function and on the last line, there is var questions = getData'~~~' . I think this is wrong in my code. How can I call the getData function out side of the DataFactory function.

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

You need to make your api calls in a 'Factory' or 'Services' file. Then make a call to the 'get' method in the Factory file in the 'Controller' file. Code separation is necessary, so take advantage of the Factories and Controllers.

Refer to example below :

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

As I mentioned in my comment, you need to inject your service into your controller. Something like this works:

(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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM