Soniya Mohan Soniya Mohan - 4 months ago 20
AngularJS Question

Pass value from provider to controller in angularJs

I'm trying get data from db to UI. Url given via provider is getting the data.

Controller in controller DetailsProvider.getDashboardDetails() is getting null.

var appmod = angular.module('project.DetailDashboardController', []);

appmod.controller("DetailDashboardController", ['$rootScope', '$scope', '$state', 'DetailsProvider',function($rootScope, $scope, $state,DetailsProvider) {
console.log("DetailDashboardController --- ");

$scope.DetList= DetailsProvider.getDashboardDetails()

}]);

})(window, window.angular);


provider which will call the list

(function(angular) {

var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});

function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});

}
};

})(window.angular);


Thanks in advance for any kind of reply!

Answer

You should return promise from your service method and do thenable in your controller.

Root Cause : your are returning the newData which will initalized later after completing the ajax call.Before completing it,you are returning the same variable which will be always null.

In service,

appmod.service('DetailsService',DetailsService); //define the DetailsService here

    function DetailsService(_$rest) {
        this._$rest = _$rest,
            this.getDashboardDetails = function(_callback, _data) {

                return _$rest.post({
                    url: window.localStorage.getItem('contextPath') + 'home/listdetail'
                });
            },
    };

and in controller,

DetailsService.getDashboardDetails().then(function(data) {

        varr holdIt = data.data.DList;

    },
    function() {

        //error handling
    })