0

I have a provider:

AdviceList.provider('$adviceList',function(){
    this.$get = function ($rootScope,$document,$compile,$http,$purr){

        function AdviceList(){

          $http.post('../sys/core/fetchTreatments.php').success(function(data,status){
                this.treatments = data;
                console.log(this.treatments); // the correct object
            });

            this.adviceCategories = [
                // available in the controller
            ];

        }
        return{

            AdviceList: function(){
                return new AdviceList();
            }
        }
    }
});

Further, i have this controller:

AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){
    var adv = $adviceList.AdviceList();
    $scope.treatments = adv.treatments; // undefined
});

Why is it, that the controller's $scope.treatments stays undefined, this.treatments inside the provider however, is filled correctly? Also, adviceCategories is available in my controller.

user2422960
  • 1,476
  • 6
  • 16
  • 28

2 Answers2

1

The call you get teatment is async in nature so the results may not have been populated when you try to assign them.

So here

var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments;  //The treatments would only get filled after the server call is over.

You need to rewrite the code in a way that you assign it to your scope property on the success callback.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
1

I will recommend you to simplify your code

1) Use simple factory method of angular instead of provider

2) return a promise to avoid using callbacks

 AdviceList.service('adviceList', function ($http) {
            return {
                adviceList: function () {
                    return $http.post('../sys/core/fetchTreatments.php');
                }
            }
        });

        AdviceList.controller('AdviceListCtrl', function ($scope, $adviceList) {
            adviceList.AdviceList().then(function (data) {
                $scope.treatments = data //set value to data when data is recieved from server
            });

        });
Ajay Beniwal
  • 18,857
  • 9
  • 81
  • 99
  • Thank you. Could you briefly explain the benefits of choosing a service over a provider, besides the less complex syntax? I would have thought that it is always a good idea to use a provider, as they are configurable. – user2422960 Jul 17 '13 at 12:30
  • Providers and services are similar and you can use any. The main issue here is not provider vs service but, handling the async nature of call. What @Ajay has suggested would work like charm. You can look at this SO question for the differences http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory – Chandermani Jul 17 '13 at 12:34