angularjsmodel-view-controllerdatepickerfactoryservice-factory

Datepicker going as Service Factory Angular


I made the classical begginers mistake and put all my business logic into my controllers instead of using services.

I have a bunch of functions which I now want to put into a service and inject this into my controllers. Generally, is there a good way to do so and how?

For example, I have a datepicker which as a default date set as of two weeks from today. I solved this in the controller like

$scope.dt=function(){
          $scope.dt=new Date();
          $scope.numberOfDaysToAdd=14;
          $scope.dt=$scope.dt.setDate($scope.dt.getDate()+$scope.numberOfDaysToAdd);

whereas in my html ng-model='dt'. I now want to take this logic and put it in a service. I thought about using a factory and I did something like this:

app.factory('Datepicker',[function(){

    var numberOfDaysToAdd=14;
    var addDays=new Date();
    addDays.daysToAdd=function(){
        addDays = addDays.setDate(addDays.getDate()+numberOfDaysToAdd);
        return addDays;
    };
    return addDays;
}]);

and in the controller

 $scope.dt = function(){
      addDays.daysToAdd()
  };

This does not work as I would expect. What's the problem here?

Cheers


Solution

  • You're on the right track of putting the logic into the factory!

    This could be one of several issues. But since you didn't post all your code for your new controller, I'll question that first: Did you inject your 'Datepicker' service into your controller?

    Secondly, the way you use the service in your controller should call the service itself (because the service returns an object):

    Say the name of your service is datePickerService and the name of your controller is dateCtrl:

    controllers.controller('dateCtrl', ['$scope', 'datePickerService', function($scope, datePickerService){
        $scope.dt = datePickerService;    //How you hook up the service to your controller
        datePickerService.addDays();   //How you could call the function as defined in your service 
    }]);
    

    Hope this helps!