用angularJs制作工厂模块的正确方法

用angularJs制作工厂模块的正确方法,angularjs,angularjs-factory,Angularjs,Angularjs Factory,我有这样一个控制器功能: $scope.localTimezone = function (userTimezone,datetime) { // .... return data; } 使其成为工厂模块的正确方法是什么?我尝试了以下操作,但出现了错误 angular.module('localTimezone', []) .factory('localTimezone',function(userTimezone,datetime) { // ...

我有这样一个控制器功能:

$scope.localTimezone = function (userTimezone,datetime) {
  // ....
  return data;
}
使其成为工厂模块的正确方法是什么?我尝试了以下操作,但出现了错误

angular.module('localTimezone',  [])
   .factory('localTimezone',function(userTimezone,datetime) {
      // ...
      return data;
   });


angular.module('app', ['localTimezone'])
   .controller('tasksController',function ($scope,localTimezone) {
     // ...
   });
我遗漏了一些概念或逻辑。有人能给我指出正确的方向吗?

控制器示例 坏的:

好:

工厂示例 坏的:

好:

有关详细指南,请浏览本博客:
下面是一个工作代码示例,它基于userTimezone和datetime是localTimezone模块的一部分的假设

以下内容已被修改

  • 工厂返回的“数据”已修改为基于工厂模式返回字符串-因为您返回的“数据”未引用任何内容
  • 构建应用程序已移至顶部。这段代码应该在执行其他代码之前执行
  • 应用程序变量已删除-我不喜欢全局变量
代码:

Codepen:(控制台中没有出现错误)


查看Angular中不同服务类型的相关信息。

-这是一篇很好的文章,介绍了Angular中的不同服务类型及其区别。我刚开始的时候帮了我。你能设置一个plunker显示问题吗假设我想要$http。。。如何注入其他服务?app.service(“”,['$http',function($http){this.yourVar=function(){…}}]);很抱歉,我没有解释清楚,如何以良好的方式在您拥有另一个服务()函数的地方进行注入({……..}-。。。。角度。模块('app')。工厂('AnotherService','AnotherService');
function MainCtrl () {
  this.doSomething = function () {

  };
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);
function MainCtrl (SomeService) {
  this.doSomething = SomeService.doSomething;
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);
function AnotherService () {

  var someValue = '';

  var someMethod = function () {

  };

  return {
    someValue: someValue,
    someMethod: someMethod
  };

}
angular
  .module('app')
  .factory('AnotherService', AnotherService);
function AnotherService () {

  var AnotherService = {};

  AnotherService.someValue = '';

  AnotherService.someMethod = function () {

  };

  return AnotherService;
}
angular
  .module('app')
  .factory('AnotherService', AnotherService);
angular.module('app', ['localTimezone']);

angular.module('localTimezone', []).factory('localTimezone',
  function(userTimezone, datetime) {
    var data = 'hello';
    return { data: data } ;
  });

angular.module('localTimezone').service('userTimezone', function() {
});

angular.module('localTimezone').service('datetime', function() {
});

angular.module('app').controller('tasksController',function ($scope,localTimezone) {
});