简体   繁体   English

Datepicker成为Service Factory Angular

[英]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' . 而在我的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 干杯

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? 但是,由于您没有为新控制器发布所有代码,因此我首先要问:您是否将“ Datepicker”服务注入了控制器?

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: 假设您的服务名称为datePickerService,而您的控制器名称为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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM