0

I am new to AngularJs and I created a service and want to call that service when a particular controller loads.

The code I used for controller is:

sampleApp.controller('ProjectAppController', function ($scope, ProjectAppService) {
    ProjectBudgetService.save().then (
        function () {
            $location.url(''); 
        },
        function () { 
            $scope.error = true;
        }
    );
}

And the code for service is here:

sampleApp.factory('ProjectBudgetService', function ($http, $q) {
    return {
        save: function () {          
            var deferred = $q.defer();

            $http.get('http://lh-cip.ultraserve.net.au/project/budget/?',
                      { headers: { 'Authorization': $.session.get("loginToken") } }
            )
            .success(function (data) {
                if(data.options=="") { 
                    alert("No Budget Option.");
                } 
                else {
                    $q.options.push.apply($q.options, data.options);
                    $q.services.forEach(function(entry){
                        alert(entry);
                    });

                    deferred.resolve(); 
                } 
            })
            .error(function (err) {
                $('#al_msg').html('<div class="alert alert-danger"><span>Error! Can\'t Complete Login Process.</span><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button></div>'); deferred.reject(); 
            });

            return deferred.promise;
        }
    };
});

The problem is that this code is not working. I don't know where is the problem. Please help me to sort it out. Thanks

4
  • Check your console, under the Network tab, is the request going through? Commented Apr 7, 2014 at 14:45
  • What do you mean with "this code is not working"? Commented Apr 7, 2014 at 14:45
  • A war of braces is going on. Can you indent the code which will help others help you? :) Commented Apr 7, 2014 at 14:48
  • Please consider reading about this common anti-pattern you have. Commented Apr 7, 2014 at 19:38

2 Answers 2

1

You defined your service/factory as ProjectBudgetService but are injecting in ProjectAppService

Seems like just a simple typo, but will prevent your service/factory from being injected into your controller properly. Check your console to see what errors you're getting.

Sign up to request clarification or add additional context in comments.

Comments

0

If you use a $watch in the controller, you can call the service when the page associated with the controller is loaded. Something like this.

$scope.$watch('$viewContentLoaded', function() {
    ProjectBudgetService.save().then( ... );
});

1 Comment

Not required. Service can be called the way OP is using now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.