Passing argument(s) to a service in AngularJs

All we need is an easy explanation of the problem, so here it is.

I am trying to configure my first tidbits of the AngularJs for a trivial stuff, but unfortunately unsuccessful at it after considerable amount of time.

My Premise:
Users select one of the options from a dropdown and have an appropriate template loaded into a div below the select. I have set up the service, a custom directive (by following the ans by @Josh David Miller on this post, and a controller in place. The ajax call in service is working fine except that the params that I pass to the server is hardcoded. I want this to be the ‘key’ from the dropdown selected by user. At the moment I am failing to have this code passed to the service.

My configuration:

    var firstModule = angular.module('myNgApp', []);

    // service that will request a server for a template
    firstModule.factory( 'katTplLoadingService', function ($http) {

        return function() {


            $http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {params:{'b1'}}
            ).success(function(template, status, headers, config){
                return template

            })
        };
    });


    firstModule.controller('KatController', function($scope, katTplLoadingService) {
        $scope.breed = {code:''}

        // here I am unsuccessfully trying to set the user selected code to a var in service, 

        //var objService = new katTplLoadingService();
        //objService.breedCode({code: $scope.breed.code});


        $scope.loadBreedData = function(){
            $scope.template = katTplLoadingService();
        }
    });



    firstModule.directive('showBreed', function ($compile) {
        return {
            scope: true,
            link: function (scope, element, attrs) {
                var el;
                attrs.$observe( 'template', function (tpl) {

                    if (angular.isDefined(tpl)) {

                        el = $compile(tpl)(scope);
                        element.html("");
                        element.append(el);
                    }
                });
            }
        };
    })

and the HTML setup is

<form ng-controller="KatController">

   <select name="catBreeds" from="${breedList}" ng-change="loadBreedData()"
         ng-model="breed.code" />

   <div>

      <div show-breed template="{{template}}"></div>

   </div>

</form>

I need the currently hardcoded value ‘b1’ in the $http ajax call to be the value in $scope.breed.code.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Your ajax request is async while your controller behaves as if the request were sync.

I assume that the get request has everything it needs to perform right.

First pass a callback to your service (note the usage of fn):

firstModule.factory( 'katTplLoadingService', function ($http) {
    return { 
        fn: function(code, callback) { //note the callback argument
            $http.get("${createLink(controller:'kats', action:'loadBreedInfo')}",
            params:{code: code}}) //place your code argument here
                .success(function (template, status, headers, config) {
                    callback(template); //pass the result to your callback
                });
        };
    };
});

In your controller:

$scope.loadBreedData = function() {
    katTplLoadingService.fn($scope.breed.code, function(tmpl) { //note the tmpl argument
        $scope.template = tmpl;
    });
}

Doing so your code is handling now your async get request.

I didn’t test it, but it must be doing the job.

Method 2

I think you defined the factory not in right way. Try this one:

firstModule.factory('katTplLoadingService', ['$resource', '$q', function ($resource, $q) {
    var factory = {
        query: function (selectedSubject) {
            $http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {
                params: {
                    'b1'
                }
            }).success(function (template, status, headers, config) {
                return template;
            })
        }
    }
    return factory;
}]);


firstModule.controller('KatController', function($scope, katTplLoadingService) {

    $scope.breed = {code:''}    

    $scope.loadBreedData = function(){
        $scope.template = katTplLoadingService.query({code: $scope.breed.code});
    }
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply