antonyboom antonyboom - 3 months ago 5
Javascript Question

angular service doesn't fire

I did pretty simple plunker to show my problem. The problem is I have variable and I want to populate this variable with initial app loading, I did angular services for this purpose, but for some reason angular services doesn't fire inside controller. Where is my mistake?

app.controller('MainCtrl', function($scope, optService) {

$scope.priority = [];

var exeService = function() {

console.log('function fired')
// this is firing
optService.myOptions(function (result) {

console.log('service fired')
// this is not firing
angular.forEach(result, function(value) {

$scope.priority.push({value: value.name, label: value.name});

});
});
}
exeService()
console.log($scope.priority)
// shows an empty array
});


services

(function () {

angular.module("app").factory("optService", ["$http", "$rootScope", "$q", "$log",
function ($http, $rootScope, $q, $log) {

var clearApi = "test.json";


function myOptions () {
return $http.get(clearApi)
.then(function (response) {
console.log(response.data)
// shows an array
return response.data;
});
}

return {
myOptions: myOptions
}

}])
}());

Answer

You should do the service declaration like that:

 app.controller('MainCtrl', ['$scope', 'optService', function($scope, optService) {

and in the controller

  optService.myOptions().then(function (result) {

    console.log('service fired')

      angular.forEach(result, function(value) {

          $scope.priority.push({value: value.name, label: value.name});

      });
  });
Comments