Passing argument(s) to a service in AngularJs

rstarter picture rstarter · Nov 10, 2013 · Viewed 38.5k times · Source

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.

Answer

roland picture roland · Nov 10, 2013

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.